linux驱动学习之内核线程分析

来源:互联网 发布:淘宝闺蜜网址 编辑:程序博客网 时间:2024/05/17 23:56
内核线程和普通的进程间的区别在于内核线程没有独立的地址空间,它只在 内核空间运行,从来不切换到用户空间去;并且和普通进程一样,可以被调度,也可以被抢占。

 

一 线程的创建

[plain] view plaincopyprint?
  1.      struct task_struct *kthread_create(int (*threadfn)(void *data), void *data, const char namefmt[], ...);  
  2.      线程创建后,不会马上运行,而是需要将kthread_create() 返回的task_struct指针传给wake_up_process()才能驱动线程。  
  3.   
  4.      也可以使用kthread_run创建线程并启动线程  
  5.      struct task_struct *kthread_run(int (*threadfn)(void *data),void *data,const char *namefmt, ...);  
  6.       
  7. #define kthread_run(threadfn, data, namefmt, ...)              \  
  8. ({                                     \  
  9.     struct task_struct *__k                        \  
  10.         = kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \  
  11.     if (!IS_ERR(__k))                          \  
  12.         wake_up_process(__k);                      \  
  13.     __k;                                   \  
  14. })  

        可见kthread_run是在调用了kthread_create后执行了wake_up_process.
        在非内核线程中调用kernel_thread,必须在调用daemonize(...)来释放资源,成为真正的内核线程,kthread_create实际调用kernel_thread但是内部已经做了处理,不需要自己调用daemonize。

二 线程的退出

      kthread_stop:设置线程的退出标记(线程函数内应用int kthread_should_stop(void)函数,当返回真时应退出函数),kthread_stop会一直等待至线程结束,线程结束前会发送完成结束给kthread_stop,如果直接使用do_exit直接退出线程那么kthread_stop不会收到完成信号将一直等待下去。如果线程已经退出那么kthread_stop会先设置退出标记再唤醒一下thread,唤醒线程后会判断退出标记因此设定的处理函数不会被调用。如果线程已经被唤醒并已经退出那么kthread_stop会一直等待。
[cpp] view plaincopyprint?
  1. int kthread_stop(struct task_struct *thread);  
  2. 如果处理函数没用kthread_should_stop判断退出,那么 kthread_stop会一直等待处理函数主动退出。  

三 源码分析 这里使用的内核版本是2.6.21.5

         3.1 管理调度其它的内核线程kthread

                 使用ps命令可以查看有个名叫kthread的进程,它在内核初始化的时候被创建。

[html] view plaincopyprint?
  1.  static __init int helper_init(void)  
  2.  {  
  3.    //创建一个单线程的共享列队  
  4.     helper_wq = create_singlethread_workqueue("kthread");  
  5.     BUG_ON(!helper_wq);  
  6.     return 0;  
  7. }  
  8. core_initcall(helper_init);  
                 就是这个共享列队kthread_create会定义一个工作,在工作内创建创建具体的线程。

         3.2 kthread_create创建线程

                   再看kthread_create前先看下kthread_create_info结构,每个线程创建时使用。

[cpp] view plaincopyprint?
  1. struct kthread_create_info  
  2. {  
  3.     /* Information passed to kthread() from keventd. */  
  4.     int (*threadfn)(void *data);              //线程处理函数  
  5.     void *data;                                        //线程参数  
  6.     struct completion started;                //在工作中等待kernel_thread创建线程完成,线程创建完后线程会通知工作继续。  
  7.   
  8.     /* Result passed back to kthread_create() from keventd. */  
  9.     struct task_struct *result;                // started当收到线程创建完信号started后,用来存放创建的任务结构体  
  10.     struct completion done;                   // 工作者线程加入一个工作后会等待工作做完,这个工作只是创建线程。   
  11.     struct work_struct work;                  // 创建线程的工作,具体工作看后面源码  
  12. };  

[cpp] view plaincopyprint?
  1. /** 
  2.  * kthread_create - 创建一个线程. 
  3.  * @threadfn: the function to run until signal_pending(current). 
  4.  * @data: data ptr for @threadfn. 
  5.  * @namefmt: printf-style name for the thread. 
  6.  * 
  7.  * 描述:这个帮助函数创建并命名一个内核线程,线程创建后并不运行,使用wake_up_process() 函数来运行,参考kthread_run(), kthread_create_on_cpu() 
  8.  * 
  9.   *被唤醒后,线程调用threadfn()函数data作为参数,如果是独立线程没有其他线程调用 kthread_stop()那么可以直接使用do_exit(),或当检测到kthread_should_stop()返回真时(kthread_stop()已被调用了)返回处理函数 ,  应返回0或负数,返回值会传给 kthread_stop()返回。 
  10.  */  
  11. struct task_struct *kthread_create(int (*threadfn)(void *data),  void *data, const char namefmt[], ...)  
  12. {  
  13.     struct kthread_create_info create;  
  14.   
  15.         //下面五行初始化kthread_create_info  
  16.     create.threadfn = threadfn;                                              
  17.     create.data = data;  
  18.     init_completion(&create.started);  
  19.     init_completion(&create.done);  
  20.     INIT_WORK(&create.work, keventd_create_kthread); //可见创建的工作是在keventd_create_kthread函数内进行  
  21.   
  22.     /*The workqueue needs to start up first:*/  
  23.     if (!helper_wq)                                                               //这个系统启动后正常是已经初始化了的  
  24.         create.work.func(&create.work);                          //如没初始化那只有在当前进程下完成工作了而不是在kthread 里  
  25.     else {  
  26.         queue_work(helper_wq, &create.work);               //将工作加入列队并调度  
  27.         wait_for_completion(&create.done);                    //等待工作执行完,执行完后create.result返回创建的任务结构或错误,由于工作是在kthread 里执行所以必须等待工作做完才能返回  
  28.     }  
  29.     if (!IS_ERR(create.result)) {  
  30.         va_list args;  
  31.         va_start(args, namefmt);  
  32.         vsnprintf(create.result->comm, sizeof(create.result->comm),  
  33.               namefmt, args);  
  34.         va_end(args);  
  35.     }  
  36.   
  37.     return create.result;  
  38. }  

上面看到创建工作是在keventd_create_kthread函数里,那么看下keventd_create_kthread函数
[cpp] view plaincopyprint?
  1. /* We are keventd: create a thread.   这个函数工作在keventd内核线程中*/  
  2. static void keventd_create_kthread(struct work_struct *work)  
  3. {  
  4.     struct kthread_create_info *create =container_of(work, struct kthread_create_info, work);  
  5.     int pid;  
  6.   
  7.     /* We want our own signal handler (we take no signals by default)*/  
  8.         /*我们使用自己的信号处理,默认不处理信号*/  
  9.         pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);//在这里创建函数,线程处理函数为kthread函数,参数为struct kthread_create_info指针create。  
  10.   
  11.     if (pid < 0) {  
  12.         create->result = ERR_PTR(pid);  
  13.     } else {  
  14.         wait_for_completion(&create->started);  //等待创建的线程执行,线程执行后会发送完成信号create->started  
  15.         read_lock(&tasklist_lock);  
  16.         create->result = find_task_by_pid(pid);  
  17.         read_unlock(&tasklist_lock);  
  18.     }  
  19.     complete(&create->done);  
  20. }  

 这时kthread_create在等待create->done信号,内核线程keventd在等待线程创建完create->started。上面创建了线程,处理函数为kthread

[cpp] view plaincopyprint?
  1. static int kthread(void *_create)  
  2. {  
  3.     struct kthread_create_info *create = _create;  
  4.     int (*threadfn)(void *data);  
  5.     void *data;  
  6.     sigset_t blocked;  
  7.     int ret = -EINTR;  
  8.   
  9.     kthread_exit_files();  
  10.   
  11.     /* Copy data: it's on keventd's stack */  
  12.     threadfn = create->threadfn;  
  13.     data = create->data;  
  14.   
  15.     /* Block and flush all signals (in case we're not from keventd). 阻塞全部信号*/  
  16.     sigfillset(&blocked);  
  17.     sigprocmask(SIG_BLOCK, &blocked, NULL);  
  18.     flush_signals(current);  
  19.   
  20.     /* By default we can run anywhere, unlike keventd. 允许线程在任意CPU上运行 keventd值在1个CPU上运行*/  
  21.     set_cpus_allowed(current, CPU_MASK_ALL);  
  22.   
  23.     /* OK, tell user we're spawned, wait for stop or wakeup */  
  24.     __set_current_state(TASK_INTERRUPTIBLE);  
  25.     complete(&create->started);                              //这里通知keventd完成线程初始化,keventd收到后获取新线程的任务结构,然后发出工作完成的信号后kthread_create返回。  
  26.     schedule();  
  27.   
  28.     if (!kthread_should_stop())                                  //判断先前是否调用过kthread_stop  
  29.         ret = threadfn(data);                                         //这里才真正执行定义的线程函数  
  30.   
  31.     /* It might have exited on its own, w/o kthread_stop.  Check. */  
  32.     if (kthread_should_stop()) {                                //判断是否执行过kthread_stop  
  33.         kthread_stop_info.err = ret;                            //ret是线程函数的返回,后面会经过kthread_stop函数返回  
  34.         complete(&kthread_stop_info.done);             //如执行过kthread_stop 还要通知kthread_stop线程完成结束了,如果用户定义的处理函数使用了do_exit那么就不会通知kthread_stop,造成kthread_stop一直等待。  
  35.     }  
  36.     return 0;  
  37. }  

至此我们看到kthread_create是如何创建线程,和线程是如何工作的了

        3.3 kthread_stop线程的停止

                先看下停止相关的结构

[cpp] view plaincopyprint?
  1. struct kthread_stop_info  
  2. {  
  3.     struct task_struct *k;           //要停止的线程结构  
  4.     int err;                                  //返回值  
  5.     struct completion done;      //线程完成结束的等待信号  
  6. };  
  7. /* Thread stopping is done by setthing this var: lock serializes multiple kthread_stop calls. */  
  8. /* 线程结束锁 kthread_stop在整个系统内一次只能被一个线程调用*/  
  9. static DEFINE_MUTEX(kthread_stop_lock);  
  10. static struct kthread_stop_info kthread_stop_info;  

[cpp] view plaincopyprint?
  1. /** 
  2.  * kthread_should_stop - should this kthread return now? 
  3.  * When someone calls kthread_stop() on your kthread, it will be woken 
  4.  * and this will return true.  You should then return, and your return 
  5.  * value will be passed through to kthread_stop(). 
  6.  */  
  7. int kthread_should_stop(void)  
  8. {  
  9.     return (kthread_stop_info.k == current);  
  10. }  
这个函数在kthread_stop()被调用后返回真,当返回为真时你的处理函数要返回,返回值会通过kthread_stop()返回。所以你的处理函数应该有判断kthread_should_stop然后退出的代码。
[cpp] view plaincopyprint?
  1. /** 
  2.  * kthread_stop - stop a thread created by kthread_create(). 
  3.  * @k: thread created by kthread_create(). 
  4.  * 
  5.  * Sets kthread_should_stop() for @k to return true, wakes it, and 
  6.  * waits for it to exit.  Your threadfn() must not call do_exit() 
  7.  * itself if you use this function!  This can also be called after 
  8.  * kthread_create() instead of calling wake_up_process(): the thread 
  9.  * will exit without calling threadfn(). 
  10.  * 
  11.  * Returns the result of threadfn(), or %-EINTR if wake_up_process() 
  12.  * was never called. 
  13.  */  
  14. int kthread_stop(struct task_struct *k)  
  15. {  
  16.     int ret;  
  17.     mutex_lock(&kthread_stop_lock);                                                            //系统一次只能处理一个结束线程申请  
  18.     /* It could exit after stop_info.k set, but before wake_up_process. */  
  19.     get_task_struct(k); //增加线程引用计数                                       
  20.     /* Must init completion *before* thread sees kthread_stop_info.k */  
  21.     init_completion(&kthread_stop_info.done);  
  22.     smp_wmb();  
  23.     /* Now set kthread_should_stop() to true, and wake it up. */  
  24.     kthread_stop_info.k = k;//设置了这个之后 kthread_should_stop()  会返回真  
  25.     wake_up_process(k);      //不管线程有没运行 先叫醒再说(如果已经唤醒过并结束了,该线程是唤醒不了的,这样会造成后面一直等待kthread_stop_info.done信号),即便没运行叫醒后也不会运行用户定义的函数。  
  26.     put_task_struct(k);  
  27.     /* Once it dies, reset stop ptr, gather result and we're done. */  
  28.     wait_for_completion(&kthread_stop_info.done);//等待线程结束  
  29.     kthread_stop_info.k = NULL;              
  30.     ret = kthread_stop_info.err;                                 //返回值    
  31.     mutex_unlock(&kthread_stop_lock);  
  32.     return ret;  
  33. }  

注意如果调用了kthread_stop你的处理函数不能调用do_exit(),函数返回你处理函数的返回值,如果创建的线程还没调用过wake_up_process()那么会返回-EINTR .


   四 测试代码

[cpp] view plaincopyprint?
  1. struct task_struct *mytask;  
  2. /*代码中要有kthread_should_stop()判断 至于返回值只对kthread_stop才有意义*/  
  3. int func(void* data)  
  4. {  
  5.   while(1 )  
  6.   {  
  7.     if( kthread_should_stop())  return -1;  
  8.     printk(KERN_ALERT "func running\n");  
  9.     set_current_state(TASK_UNINTERRUPTIBLE);  
  10.       schedule_timeout(1*HZ);  
  11.   }   
  12.   return 0;  
  13. }  
  14.   
  15. 线程创建和驱动  
  16. mytask=kthread_create(func,0,"mykthread");  
  17. wake_up_process(mytask);  
  18.   
  19. 在需要结束的地方调用  
  20.  kthread_stop(mytask);  

        通过几个函数可以很容易的创建内核线程,但线程创建出来之后我们更关注的是有多线程带来的并发和竞争问题。并发的管理是操作系统编程的核心问题之一,引起的错误是一些最易出现又最难发现的问题.
1 0