1. 程式人生 > >Linux核心多執行緒實現方法

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);