Linux内核:kthread_create(线程)、SLEEP_MILLI_SEC

转自:http://blog.csdn.net/guowenyan001/article/details/39230181

一、代码

[cpp] view plain copy
 
  1. #include <linux/module.h>  
  2. #include <linux/kernel.h>  
  3. #include <linux/types.h>  
  4. #include <linux/kthread.h>  
  5. #include <linux/err.h>  
  6.   
  7.   
  8. MODULE_VERSION("1.0.0_0");  
  9. MODULE_LICENSE("GPL");  
  10. MODULE_AUTHOR("gwy");  
  11.   
  12.   
  13.   
  14. #ifndef SLEEP_MILLI_SEC  
  15. #define SLEEP_MILLI_SEC(nMilliSec)   
  16.     do {   
  17.         long timeout = (nMilliSec) * HZ /1000;   
  18.         while (timeout > 0)   
  19.         {   
  20.             timeout = schedule_timeout(timeout);   
  21.         }   
  22.     }while (0);  
  23. #endif  
  24.   
  25.   
  26. struct task_struct* thread = NULL;  
  27.   
  28. void thread_proc(void* arg)  
  29. {  
  30.     struct timespec ts;    
  31.   
  32.     //set_current_state(TASK_UNINTERRUPTIBLE);  
  33.     while(!kthread_should_stop())  
  34.     {  
  35.         ts = current_kernel_time();    
  36.         printk("thread_proc:%s. time:%ld ", (char*)arg, ts.tv_sec);  
  37.           
  38.         SLEEP_MILLI_SEC(1000);  
  39.     }  
  40. }  
  41.   
  42. static int init_marker(void)  
  43. {  
  44.     int err;  
  45.   
  46.     printk("init marker. ");  
  47.   
  48.     thread = kthread_create(thread_proc, "thread arg", "my_thread%d", 0);  
  49.     if (IS_ERR(thread))  
  50.     {  
  51.         err = PTR_ERR(thread);  
  52.         printk("kthread_create fail. ");  
  53.         return err;  
  54.     }  
  55.   
  56.     wake_up_process(thread);  
  57.   
  58.     printk("thread create. ");  
  59.   
  60.     return 0;  
  61. }  
  62.   
  63. static void exit_marker(void)  
  64. {  
  65.     if (thread)  
  66.     {  
  67.         kthread_stop(thread);  
  68.         thread = NULL;  
  69.         printk("thread stop. ");  
  70.     }  
  71.   
  72.     printk("exit marker. ");  
  73. }  
  74.   
  75.   
  76. module_init(init_marker);  
  77. module_exit(exit_marker);  


二、输出结果

三、注意

        1)在调用kthread_stop函数时,线程函数不能已经运行结束。否则,kthread_stop函数会一直进行等待。

        2)线程函数必须能让出CPU,以便能运行其他线程。  同时线程函数也必须能重新被调度运行。

        3)注意线程函数的使用,参见“kthread_create的简单使用”。

参考资料:

        kthread_create的简单使用:http://blog.csdn.net/newnewman80/article/details/7050090

        kthread_create与kerne_thread的区别:http://blog.sina.com.cn/s/blog_5a1e1b770100jfc0.html

原文地址:https://www.cnblogs.com/x_wukong/p/6054420.html