Linux内核——线程

原文出处:http://blog.csdn.net/fontlose/article/details/8291674

目录(?)[-]

  1. 一线程的创建

  2. 二线程的退出

  3. 三源码分析这里使用的内核版本是26215

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

    2. kthread_create创建线程

    3. kthread_stop线程的停止

  4. 四测试代码

内核线程和普通的进程间的区别在于内核线程没有独立的地址空间,它只在内核空间运行,从来不切换到用户空间去;并且和普通进程一样,可以被调度,也可以被抢占。

一线程的创建

  1. structtask_struct*kthread_create(int(*threadfn)(void*data),void*data,constcharnamefmt[],...);

  2. 线程创建后,不会马上运行,而是需要将kthread_create()返回的task_struct指针传给wake_up_process()才能驱动线程。

  3. 也可以使用kthread_run创建线程并启动线程

  4. structtask_struct*kthread_run(int(*threadfn)(void*data),void*data,constchar*namefmt,...);

  5. #definekthread_run(threadfn,data,namefmt,...)\

  6. ({\

  7. structtask_struct*__k\

  8. =kthread_create(threadfn,data,namefmt,##__VA_ARGS__);\

  9. if(!IS_ERR(__k))\

  10. wake_up_process(__k);\

  11. __k;\

  12. })

     struct task_struct *kthread_create(int (*threadfn)(void *data), void *data, const char namefmt[], ...);
     线程创建后,不会马上运行,而是需要将kthread_create() 返回的task_struct指针传给wake_up_process()才能驱动线程。

     也可以使用kthread_run创建线程并启动线程
     struct task_struct *kthread_run(int (*threadfn)(void *data),void *data,const char *namefmt, ...);
    
#define kthread_run(threadfn, data, namefmt, ...)			   \
({									   \
	struct task_struct *__k						   \
		= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \
	if (!IS_ERR(__k))						   \
		wake_up_process(__k);					   \
	__k;								   \
})

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

二线程的退出

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

  2. 如果处理函数没用kthread_should_stop判断退出,那么kthread_stop会一直等待处理函数主动退出。

   int kthread_stop(struct task_struct *thread);
   如果处理函数没用kthread_should_stop判断退出,那么 kthread_stop会一直等待处理函数主动退出。

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

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

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

  1. static__initinthelper_init(void)

  2. {

  3. //创建一个单线程的共享列队

  4. helper_wq=create_singlethread_workqueue("kthread");

  5. BUG_ON(!helper_wq);

  6. return0;

  7. }

  8. core_initcall(helper_init);

          static __init int helper_init(void)
          {
            //创建一个单线程的共享列队
             helper_wq = create_singlethread_workqueue("kthread");
             BUG_ON(!helper_wq);
             return 0;
         }
         core_initcall(helper_init);
就是这个共享列队kthread_create会定义一个工作,在工作内创建创建具体的线程。

3.2kthread_create创建线程

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

  1. structkthread_create_info

  2. {

  3. /*Informationpassedtokthread()fromkeventd.*/

  4. int(*threadfn)(void*data);//线程处理函数

  5. void*data;//线程参数

  6. structcompletionstarted;//在工作中等待kernel_thread创建线程完成,线程创建完后线程会通知工作继续。

  7. /*Resultpassedbacktokthread_create()fromkeventd.*/

  8. structtask_struct*result;//started当收到线程创建完信号started后,用来存放创建的任务结构体

  9. structcompletiondone;//工作者线程加入一个工作后会等待工作做完,这个工作只是创建线程。

  10. structwork_structwork;//创建线程的工作,具体工作看后面源码

  11. };

struct kthread_create_info
{
	/* Information passed to kthread() from keventd. */
	int (*threadfn)(void *data);              //线程处理函数
	void *data;                                        //线程参数
	struct completion started;                //在工作中等待kernel_thread创建线程完成,线程创建完后线程会通知工作继续。

	/* Result passed back to kthread_create() from keventd. */
	struct task_struct *result;                // started当收到线程创建完信号started后,用来存放创建的任务结构体
	struct completion done;                   // 工作者线程加入一个工作后会等待工作做完,这个工作只是创建线程。 
	struct work_struct work;                  // 创建线程的工作,具体工作看后面源码
};

  1. /**

  2. *kthread_create-创建一个线程.

  3. *@threadfn:thefunctiontorununtilsignal_pending(current).

  4. *@data:dataptrfor@threadfn.

  5. *@namefmt:printf-stylenameforthethread.

  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. structtask_struct*kthread_create(int(*threadfn)(void*data),void*data,constcharnamefmt[],...)

  12. {

  13. structkthread_create_infocreate;

  14. //下面五行初始化kthread_create_info

  15. create.threadfn=threadfn;

  16. create.data=data;

  17. init_completion(&create.started);

  18. init_completion(&create.done);

  19. INIT_WORK(&create.work,keventd_create_kthread);//可见创建的工作是在keventd_create_kthread函数内进行

  20. /*Theworkqueueneedstostartupfirst:*/

  21. if(!helper_wq)//这个系统启动后正常是已经初始化了的

  22. create.work.func(&create.work);//如没初始化那只有在当前进程下完成工作了而不是在kthread里

  23. else{

  24. queue_work(helper_wq,&create.work);//将工作加入列队并调度

  25. wait_for_completion(&create.done);//等待工作执行完,执行完后create.result返回创建的任务结构或错误,由于工作是在kthread里执行所以必须等待工作做完才能返回

  26. }

  27. if(!IS_ERR(create.result)){

  28. va_listargs;

  29. va_start(args,namefmt);

  30. vsnprintf(create.result->comm,sizeof(create.result->comm),

  31. namefmt,args);

  32. va_end(args);

  33. }

  34. returncreate.result;

  35. }

/**
 * kthread_create - 创建一个线程.
 * @threadfn: the function to run until signal_pending(current).
 * @data: data ptr for @threadfn.
 * @namefmt: printf-style name for the thread.
 *
 * 描述:这个帮助函数创建并命名一个内核线程,线程创建后并不运行,使用wake_up_process() 函数来运行,参考kthread_run(), kthread_create_on_cpu()
 *
  *被唤醒后,线程调用threadfn()函数data作为参数,如果是独立线程没有其他线程调用 kthread_stop()那么可以直接使用do_exit(),或当检测到kthread_should_stop()返回真时(kthread_stop()已被调用了)返回处理函数 ,  应返回0或负数,返回值会传给 kthread_stop()返回。
 */
struct task_struct *kthread_create(int (*threadfn)(void *data),  void *data, const char namefmt[], ...)
{
	struct kthread_create_info create;

        //下面五行初始化kthread_create_info
	create.threadfn = threadfn;                                            
	create.data = data;
	init_completion(&create.started);
	init_completion(&create.done);
	INIT_WORK(&create.work, keventd_create_kthread); //可见创建的工作是在keventd_create_kthread函数内进行

	/*The workqueue needs to start up first:*/
	if (!helper_wq)                                                               //这个系统启动后正常是已经初始化了的
		create.work.func(&create.work);                          //如没初始化那只有在当前进程下完成工作了而不是在kthread 里
	else {
		queue_work(helper_wq, &create.work);               //将工作加入列队并调度
		wait_for_completion(&create.done);                    //等待工作执行完,执行完后create.result返回创建的任务结构或错误,由于工作是在kthread 里执行所以必须等待工作做完才能返回
	}
	if (!IS_ERR(create.result)) {
		va_list args;
		va_start(args, namefmt);
		vsnprintf(create.result->comm, sizeof(create.result->comm),
			  namefmt, args);
		va_end(args);
	}

	return create.result;
}

上面看到创建工作是在keventd_create_kthread函数里,那么看下keventd_create_kthread函数

  1. /*Wearekeventd:createathread.这个函数工作在keventd内核线程中*/

  2. staticvoidkeventd_create_kthread(structwork_struct*work)

  3. {

  4. structkthread_create_info*create=container_of(work,structkthread_create_info,work);

  5. intpid;

  6. /*Wewantourownsignalhandler(wetakenosignalsbydefault)*/

  7. /*我们使用自己的信号处理,默认不处理信号*/

  8. pid=kernel_thread(kthread,create,CLONE_FS|CLONE_FILES|SIGCHLD);//在这里创建函数,线程处理函数为kthread函数,参数为structkthread_create_info指针create。

  9. if(pid<0){

  10. create->result=ERR_PTR(pid);

  11. }else{

  12. wait_for_completion(&create->started);//等待创建的线程执行,线程执行后会发送完成信号create->started

  13. read_lock(&tasklist_lock);

  14. create->result=find_task_by_pid(pid);

  15. read_unlock(&tasklist_lock);

  16. }

  17. complete(&create->done);

  18. }

/* We are keventd: create a thread.   这个函数工作在keventd内核线程中*/
static void keventd_create_kthread(struct work_struct *work)
{
	struct kthread_create_info *create =container_of(work, struct kthread_create_info, work);
	int pid;

	/* We want our own signal handler (we take no signals by default)*/
        /*我们使用自己的信号处理,默认不处理信号*/
        pid = kernel_thread(kthread, create, CLONE_FS | CLONE_FILES | SIGCHLD);//在这里创建函数,线程处理函数为kthread函数,参数为struct kthread_create_info指针create。

	if (pid < 0) {
		create->result = ERR_PTR(pid);
	} else {
		wait_for_completion(&create->started);  //等待创建的线程执行,线程执行后会发送完成信号create->started
		read_lock(&tasklist_lock);
		create->result = find_task_by_pid(pid);
		read_unlock(&tasklist_lock);
	}
	complete(&create->done);
}

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

  1. staticintkthread(void*_create)

  2. {

  3. structkthread_create_info*create=_create;

  4. int(*threadfn)(void*data);

  5. void*data;

  6. sigset_tblocked;

  7. intret=-EINTR;

  8. kthread_exit_files();

  9. /*Copydata:it'sonkeventd'sstack*/

  10. threadfn=create->threadfn;

  11. data=create->data;

  12. /*Blockandflushallsignals(incasewe'renotfromkeventd).阻塞全部信号*/

  13. sigfillset(&blocked);

  14. sigprocmask(SIG_BLOCK,&blocked,NULL);

  15. flush_signals(current);

  16. /*Bydefaultwecanrunanywhere,unlikekeventd.允许线程在任意CPU上运行keventd值在1个CPU上运行*/

  17. set_cpus_allowed(current,CPU_MASK_ALL);

  18. /*OK,telluserwe'respawned,waitforstoporwakeup*/

  19. __set_current_state(TASK_INTERRUPTIBLE);

  20. complete(&create->started);//这里通知keventd完成线程初始化,keventd收到后获取新线程的任务结构,然后发出工作完成的信号后kthread_create返回。

  21. schedule();

  22. if(!kthread_should_stop())//判断先前是否调用过kthread_stop

  23. ret=threadfn(data);//这里才真正执行定义的线程函数

  24. /*Itmighthaveexitedonitsown,w/okthread_stop.Check.*/

  25. if(kthread_should_stop()){//判断是否执行过kthread_stop

  26. kthread_stop_info.err=ret;//ret是线程函数的返回,后面会经过kthread_stop函数返回

  27. complete(&kthread_stop_info.done);//如执行过kthread_stop还要通知kthread_stop线程完成结束了,如果用户定义的处理函数使用了do_exit那么就不会通知kthread_stop,造成kthread_stop一直等待。

  28. }

  29. return0;

  30. }

static int kthread(void *_create)
{
	struct kthread_create_info *create = _create;
	int (*threadfn)(void *data);
	void *data;
	sigset_t blocked;
	int ret = -EINTR;

	kthread_exit_files();

	/* Copy data: it's on keventd's stack */
	threadfn = create->threadfn;
	data = create->data;

	/* Block and flush all signals (in case we're not from keventd). 阻塞全部信号*/
	sigfillset(&blocked);
	sigprocmask(SIG_BLOCK, &blocked, NULL);
	flush_signals(current);

	/* By default we can run anywhere, unlike keventd. 允许线程在任意CPU上运行 keventd值在1个CPU上运行*/
	set_cpus_allowed(current, CPU_MASK_ALL);

	/* OK, tell user we're spawned, wait for stop or wakeup */
	__set_current_state(TASK_INTERRUPTIBLE);
	complete(&create->started);                              //这里通知keventd完成线程初始化,keventd收到后获取新线程的任务结构,然后发出工作完成的信号后kthread_create返回。
	schedule();

	if (!kthread_should_stop())                                  //判断先前是否调用过kthread_stop
		ret = threadfn(data);                                         //这里才真正执行定义的线程函数

	/* It might have exited on its own, w/o kthread_stop.  Check. */
	if (kthread_should_stop()) {                                //判断是否执行过kthread_stop
		kthread_stop_info.err = ret;                            //ret是线程函数的返回,后面会经过kthread_stop函数返回
		complete(&kthread_stop_info.done);             //如执行过kthread_stop 还要通知kthread_stop线程完成结束了,如果用户定义的处理函数使用了do_exit那么就不会通知kthread_stop,造成kthread_stop一直等待。
	}
	return 0;
}

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

3.3kthread_stop线程的停止

先看下停止相关的结构

  1. structkthread_stop_info

  2. {

  3. structtask_struct*k;//要停止的线程结构

  4. interr;//返回值

  5. structcompletiondone;//线程完成结束的等待信号

  6. };

  7. /*Threadstoppingisdonebysetthingthisvar:lockserializesmultiplekthread_stopcalls.*/

  8. /*线程结束锁kthread_stop在整个系统内一次只能被一个线程调用*/

  9. staticDEFINE_MUTEX(kthread_stop_lock);

  10. staticstructkthread_stop_infokthread_stop_info;

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

  1. /**

  2. *kthread_should_stop-shouldthiskthreadreturnnow?

  3. *Whensomeonecallskthread_stop()onyourkthread,itwillbewoken

  4. *andthiswillreturntrue.Youshouldthenreturn,andyourreturn

  5. *valuewillbepassedthroughtokthread_stop().

  6. */

  7. intkthread_should_stop(void)

  8. {

  9. return(kthread_stop_info.k==current);

  10. }

/**
 * kthread_should_stop - should this kthread return now?
 * When someone calls kthread_stop() on your kthread, it will be woken
 * and this will return true.  You should then return, and your return
 * value will be passed through to kthread_stop().
 */
int kthread_should_stop(void)
{
	return (kthread_stop_info.k == current);
}
这个函数在kthread_stop()被调用后返回真,当返回为真时你的处理函数要返回,返回值会通过kthread_stop()返回。所以你的处理函数应该有判断kthread_should_stop然后退出的代码。

  1. /**

  2. *kthread_stop-stopathreadcreatedbykthread_create().

  3. *@k:threadcreatedbykthread_create().

  4. *

  5. *Setskthread_should_stop()for@ktoreturntrue,wakesit,and

  6. *waitsforittoexit.Yourthreadfn()mustnotcalldo_exit()

  7. *itselfifyouusethisfunction!Thiscanalsobecalledafter

  8. *kthread_create()insteadofcallingwake_up_process():thethread

  9. *willexitwithoutcallingthreadfn().

  10. *

  11. *Returnstheresultofthreadfn(),or%-EINTRifwake_up_process()

  12. *wasnevercalled.

  13. */

  14. intkthread_stop(structtask_struct*k)

  15. {

  16. intret;

  17. mutex_lock(&kthread_stop_lock);//系统一次只能处理一个结束线程申请

  18. /*Itcouldexitafterstop_info.kset,butbeforewake_up_process.*/

  19. get_task_struct(k);//增加线程引用计数

  20. /*Mustinitcompletion*before*threadseeskthread_stop_info.k*/

  21. init_completion(&kthread_stop_info.done);

  22. smp_wmb();

  23. /*Nowsetkthread_should_stop()totrue,andwakeitup.*/

  24. kthread_stop_info.k=k;//设置了这个之后kthread_should_stop()会返回真

  25. wake_up_process(k);//不管线程有没运行先叫醒再说(如果已经唤醒过并结束了,该线程是唤醒不了的,这样会造成后面一直等待kthread_stop_info.done信号),即便没运行叫醒后也不会运行用户定义的函数。

  26. put_task_struct(k);

  27. /*Onceitdies,resetstopptr,gatherresultandwe'redone.*/

  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. returnret;

  33. }

/**
 * kthread_stop - stop a thread created by kthread_create().
 * @k: thread created by kthread_create().
 *
 * Sets kthread_should_stop() for @k to return true, wakes it, and
 * waits for it to exit.  Your threadfn() must not call do_exit()
 * itself if you use this function!  This can also be called after
 * kthread_create() instead of calling wake_up_process(): the thread
 * will exit without calling threadfn().
 *
 * Returns the result of threadfn(), or %-EINTR if wake_up_process()
 * was never called.
 */
int kthread_stop(struct task_struct *k)
{
	int ret;
	mutex_lock(&kthread_stop_lock);                                                            //系统一次只能处理一个结束线程申请
	/* It could exit after stop_info.k set, but before wake_up_process. */
	get_task_struct(k); //增加线程引用计数                                     
	/* Must init completion *before* thread sees kthread_stop_info.k */
	init_completion(&kthread_stop_info.done);
	smp_wmb();
	/* Now set kthread_should_stop() to true, and wake it up. */
	kthread_stop_info.k = k;//设置了这个之后 kthread_should_stop()  会返回真
	wake_up_process(k);      //不管线程有没运行 先叫醒再说(如果已经唤醒过并结束了,该线程是唤醒不了的,这样会造成后面一直等待kthread_stop_info.done信号),即便没运行叫醒后也不会运行用户定义的函数。
	put_task_struct(k);
	/* Once it dies, reset stop ptr, gather result and we're done. */
	wait_for_completion(&kthread_stop_info.done);//等待线程结束
	kthread_stop_info.k = NULL;            
	ret = kthread_stop_info.err;                                 //返回值  
	mutex_unlock(&kthread_stop_lock);
	return ret;
}

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


四测试代码

  1. structtask_struct*mytask;

  2. /*代码中要有kthread_should_stop()判断至于返回值只对kthread_stop才有意义*/

  3. intfunc(void*data)

  4. {

  5. while(1)

  6. {

  7. if(kthread_should_stop())return-1;

  8. printk(KERN_ALERT"funcrunning\n");

  9. set_current_state(TASK_UNINTERRUPTIBLE);

  10. schedule_timeout(1*HZ);

  11. }

  12. return0;

  13. }

  14. 线程创建和驱动

  15. mytask=kthread_create(func,0,"mykthread");

  16. wake_up_process(mytask);

  17. 在需要结束的地方调用

  18. kthread_stop(mytask);

struct task_struct *mytask;
/*代码中要有kthread_should_stop()判断 至于返回值只对kthread_stop才有意义*/
int func(void* data)
{
  while(1 )
  {
    if( kthread_should_stop())  return -1;
    printk(KERN_ALERT "func running\n");
    set_current_state(TASK_UNINTERRUPTIBLE);
	  schedule_timeout(1*HZ);
  }	
  return 0;
}

线程创建和驱动
mytask=kthread_create(func,0,"mykthread");
wake_up_process(mytask);

在需要结束的地方调用
 kthread_stop(mytask);

通过几个函数可以很容易的创建内核线程,但线程创建出来之后我们更关注的是有多线程带来的并发和竞争问题。并发的管理是操作系统编程的核心问题之一,引起的错误是一些最易出现又最难发现的问题。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章