linux建立執行緒 建立Linux核心執行緒

2021-10-18 08:12:38 字數 2850 閱讀 7356

執行緒(thread)是作業系統能夠進行運算排程的最小單位。它被包含在程序之中,是程序中的實際運作單位。乙個執行緒指的是程序中乙個單一順序的控制流,乙個程序中可以併發多個執行緒,每個執行緒並行執行不同的任務。

很多時候會需要在後台執行一些任務,比如做乙個需要實時監控某個模組狀態的debug功能,這種任務可以通過核心執行緒實現。

標頭檔案

//wake_up_process()#include //kthread_create(), kthread_run()#include //is_err()、ptr_err()#include
操作執行緒的步驟:

1.建立執行緒kthread_create

2.喚醒執行緒wake_up_process

3.結束執行緒kthread_stop

*另外linux也提供了介面kthread_run將1和2整合成乙個步驟。

建立執行緒kthread_create

kthread_create是kthread_create_on_node的巨集定義,建立執行緒後不會馬上執行,其原始碼如下:

#define kthread_create(threadfn, data, namefmt, arg...) \    kthread_create_on_node(threadfn, data, numa_no_node, namefmt, ##arg)
kthread_create_on_node的定義在檔案kernel/kthread.c中,原型如下:

__printf(4, 5)struct task_struct *kthread_create_on_node(              int (*threadfn)(void *data),              void *data,              int node,              const char namefmt, ...);
引數說明threadfn:執行緒函式,即開啟執行緒後需要call的api;

data:執行緒函式的形參,可以是null;

namefmt:執行緒名稱;

返回值:執行緒指標strcut task_struct *;

喚醒執行緒wake_up_process

使用kthread_create建立執行緒後,需要將返回值

(struct task_struct *)作為引數傳入wake_up_process()將執行緒喚醒,執行緒才會跑起來,原型:

extern int wake_up_process(struct task_struct *tsk);
建立並執行執行緒kthread_runkthread_run是將kthread_create以及wake_up_process整合的巨集定義,建立執行緒並執行,原始碼如下:

#define kthread_run(threadfn, data, namefmt, ...)  \()
結束執行緒kthread_stop將建立執行緒時返回的執行緒指標(struct task_struct *)作為引數傳入kthread_stop(),設定結束標誌should_stop,原型:

int kthread_stop(struct task_struct *k);

set_freezable()//將執行緒設定成可凍結,如果系統會休眠,則需要使用kthread_should_stop()//檢查執行緒的結束標誌should_stop並返回set_current_state()//設定執行緒任務的當前狀態,引數巨集定義在標頭檔案include/linux/sched.h中
建立執行緒例項lunuxmemo_kthread.c

Linux建立子執行緒

建立乙個子執行緒函式 utili.h include include include include using namespace std pthread.h include utili.h void thread fun void arg printf this is child id d n ...

Linux 核心執行緒建立

在linux核心中,建立執行緒函式為 kthread create on node 需要注意的是核心建立乙個核心執行緒是個非同步過程。函式 kthread create on node對外提供兩個函式一,kthread create worker二,kthread create on node當然我...

初學Linux執行緒建立

程序程序是資源 cpu 記憶體等 分配的基本單位,它是程式執行時的乙個例項。執行緒執行緒是一條執行路徑,是程式執行時的最小單位,它是程序的乙個執行流,是cpu排程和分派的基本單位,乙個程序可以由很多個執行緒組成,執行緒間共享程序的所有資源,每個執行緒有自己的堆疊和區域性變數。執行緒是一條可以執行的路...