Linux内核多线程实现方法

参考:http://blog.csdn.net/sharecode/article/details/40076951

1.创建线程方法1

kthread_create:       创建线程;改函数创建线程后,不会马上运行

wake_up_process():激活线程运行


struct task_struct *kthread_create(int (*threadfn)(void *data),void *data,const char *namefmt, ...);

//注意,第二个参数data用于向线程传递参数;线程创建后,不会马上运行,而是需要将kthread_create() 返回的task_struct指针传给wake_up_process(),然后通过此函数运行线程.

实例

  struct task_struct *ktask;

        ktask = kthread_create(test_thread, &parm1, "ktask1");
       if (IS_ERR(ktask)) {
        err = PTR_ERR(ktask);
         printk( "cannot spawn ktask1,error %d\n", err);
         goto out;
      }
      wake_up_process(ktask);

    

 test_thread 实现

int   test_thread(void *data){
        …
        while(1){
               set_current_state(TASK_UNINTERRUPTIBLE);
               if(kthread_should_stop()) break;
               if(){//条件为真
                      //进行业务处理
               }
               else{//条件为假
                      //让出CPU运行其他线程,并在指定的时间内重新被调度
                      schedule_timeout(HZ);
               }
        }
        …
        return 0;
}

2.创建线程方法2

  kthread_run :创建并启动线程的函数,相当于kthread_create +  wake_up_process功能

      ktask = kthread_run(test_thread, &parm1, "ktask1");
      if (IS_ERR(ktaskl)) {
        pr_err(" thread creation failed");
        ktaskl = NULL;
    }

3.终止线程

   int kthread_stop(struct task_struct *k);

   if(ktask){

   kthread_stop(ktask);

    ktask=NULL;

  }

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

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

4.设置实时线程优先级

     struct task_struct *t;
     struct sched_param param = {
        .sched_priority = MAX_USER_RT_PRIO/2,
    };
    t = kthread_create(irq_thread, new, "irq/%d-s-%s", irq,
                   new->name);

    if (IS_ERR(t))
        return PTR_ERR(t);

     sched_setscheduler_nocheck(t, SCHED_FIFO, &param);

      wake_up_process(t);

猜你喜欢

转载自blog.csdn.net/yellowblue2/article/details/86413007