kernel-執行緒thread

迷霧綠洲發表於2014-12-15


kernel執行緒管理在2.6 一般是:

#include<pthread.h>

pthread_ttid; sigset_tset;
voidmyfunc()
{
 printf("hello\n");
}
intmain(){
創造執行緒

pthread_create(&tid,NULL,mythread,NULL);

退出執行緒

pthread_kill(tid,SIGUSR2);

等待執行緒結束

pthread_join(tid,&status);

}

到了3.0 提出了一個更加簡單的執行緒管理方法:

kthread_create:建立執行緒。

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, ...);
kthread_stop:通過傳送訊號給執行緒,使之退出。
int kthread_stop(struct task_struct *thread);
執行緒一旦啟動起來後,會一直執行,除非該執行緒主動呼叫do_exit函式,或者其他的程式呼叫kthread_stop函式,結束執行緒的執行。

但如果執行緒函式正在處理一個非常重要的任務,它不會被中斷的。當然如果執行緒函式永遠不返回並且不檢查訊號,它將永遠都不會停止。

引用檔案

#include <linux/kthread.h>

創造執行緒結構

staticstruct task_struct *test_task;

test_task = kthread_create(test_thread, NULL, "test_task");

啟動執行緒

wake_up_process(test_task);

關閉執行緒

  kthread_stop(test_task);

相關文章