執行緒函式(建立 取消 等待)

2021-05-24 23:34:47 字數 2323 閱讀 2003

1.建立執行緒

建立執行緒的函式定義如下:

#include

int pthread_create(pthread_t  *restrict  thread ,const  pthread_attr_t  *restrict  attr,void  *(*start_routine )(void*),void  *restrict arg) ;

引數thread返回建立執行緒的id 。attr用來設定執行緒的屬性,一般置為null,引數start_routine是乙個函式指標,指向乙個函式 ,這個函式就是執行緒要執行的**;arg引數 是start_routine指向的函式傳入的引數。

#include //執行緒程式大多使用pthread庫

#include

#include

void* thread_func(void *arg)  //執行緒函式

int main()

直接gcc thread.c會報錯,因為thread庫不是linux的標準庫,需要給編譯器制定鏈結的庫,使用gcc thread.c -lpthread命令後輸入gcc thread.c仍報錯:

/tmp/ccs2nyso.o: in function `main':

thread.c:(.text+0x67): undefined reference to `pthread_create'

collect2: ld returned 1 exit status

解決辦法 :gcc -o thread thread.c -lpthread

./thread.c

得到輸出如下 :

hi,i'm a thread!

argument set:100

main thread!

2.取消執行緒

函式定義如下:

#include

int pthread_cancel(pthtead_t thread); //其中thread為執行緒id

#include //執行緒程式大多使用pthread庫

#include

#include

void* thread_func(void *arg)  //執行緒函式

}int main()

執行結果如下:

hi,i'm a thread!

argument set:100

(列印若干次引數值)

main thread!

3.等待執行緒

在上面例子中,主線程使用sleep()函式暫停自己的執行,等待新建立的程序結束。但對於複雜點的程式延時函式就不好用了。

使用pthread_join()函式等待乙個程序結束,函式定義如下:

#include

int pthread_jion(pthread_t  thread,void **value_ptr);

引數thread是要等待執行緒的id,引數value_ptr指向的是退出執行緒的返回值。如果被等待執行緒成功返回,函式返回0,其他其他情況返回出錯**。

4.多執行緒例項

在主程式中建立兩個執行緒mid_thread和term_thread,mid執行緒不斷等待term執行緒終止它,並且每隔2秒列印一次等待的次數。term接收從主函式傳進來的mid執行緒的id。如果執行緒id合法,就呼叫pthread_cancel()函式結束mid執行緒。

#include

#include

#include

#include

void* mid_thread(void *arg);  //mid執行緒宣告

void* term_thread(void *arg); //term執行緒宣告

int main()

if(pthread_create(&term_tid,null,term_thread,(void*)&mid_thread))   //建立term執行緒

if(pthread_join(mid_tid,null))   //等待mid執行緒結束

if(pthread_join(term_tid,null))  //等待term執行緒結束

return 0;

}void* mid_thread(void *arg)  //mid執行緒定義

}void* term_thread(void *arg)   //term執行緒定義

}"li.c" 56 lines, 897 characters

輸出結果為:

mid thread create!

waiting term thread 0 times!

term thread created!

waiting term thread 1 times!

LINUX多執行緒程式設計之建立,等待,取消執行緒

h7n9禽流感來啦,多人死亡,又感覺到了03年我在北京時的非典氣氛。家裡菜桌上肉明顯沒了。睡一覺起來,肚子裡再沒有肉貨,清明節學習的計畫不能停止!現在進入多執行緒學習啦。由於linux程序間的通訊占用資源蠻大的,所以設定了執行緒函式,只複製棧,其它同享。當然,執行緒之間,也存在著同步機制啦 互斥鎖,...

執行緒建立等待及退出

1.linux上線程開發api概要 多執行緒開發在 linux 平台上已經有成熟的 pthread 庫支援,在程式執行的時候要假如 lpthread 其涉及的多執行緒開發的最基本概念主要包含三點 執行緒,互斥鎖,條件。其中,執行緒操作又分執行緒的建立,退出,等待 3 種。互斥鎖則包括 4 種操作,分...

Linux執行緒 執行緒建立 等待 分離 優先順序

建立執行緒,等待執行緒終止 分離執行緒pthread detach 可以顯式用於分離執行緒,儘管建立時是可連線的。建立乙個執行緒預設的狀態是joinable,如果乙個執行緒結束執行但沒有被join,則它的狀態類似於程序中的zombie process,即還有一部分資源沒有被 退出狀態碼 所以建立執行...