pthread 使用者態建立執行緒

2021-06-20 17:54:14 字數 1750 閱讀 7804

/*thread.c*/  

#include #include /*執行緒一*/

void thread_1(void)

pthread_exit(0);

}

/*執行緒二*/

void thread_2(void)

pthread_exit(0);

}

int main(void)

/*建立執行緒二*/

ret = pthread_create(&id_2, null, (void *)thread_2, null);

if(ret != 0)

/*等待執行緒結束*/

pthread_join(id_1, null);

pthread_join(id_2, null);

return 0;

} //gcc pthread.c -lpthread

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,

void *(*start_routine) (void *), void *arg);

pthread_t *thread指向執行緒識別符號的指標。

pthread_attr_t *attr 設定的

執行緒屬性。

void *(*start_routine) (void *) 

執行緒執行函式的起始位址。

void *arg 

執行函式的引數。

返回值若執行緒建立成功,則返回0。若執行緒建立失敗,則返回出錯編號,並且*thread中的內容是未定義的。

返回成功時,由tidp指向的記憶體單元被設定為新建立執行緒的執行緒id。attr引數用於指定各種不同的執行緒屬性。新建立的執行緒從start_rtn函式的位址開始執行,該函式只有乙個萬能指標引數arg,如果需要向start_rtn函式傳遞的引數不止乙個,那麼需要把這些引數放到乙個結構中,然後把這個結構的位址作為arg的引數傳入。

linux下用c語言開發多執行緒程式,linux系統下的多執行緒遵循posix執行緒介面,稱為pthread。

注意事項:

因為pthread並非linux系統的預設庫,而是posix執行緒庫。在linux中將其作為乙個庫來使用,因此加上 -lpthread(或-pthread)以顯式鏈結該庫。函式在執行錯誤時的錯誤資訊將作為返回值返回,並不修改系統全域性變數errno,當然也無法使用perror()列印錯誤資訊。

標頭檔案 : #include

函式定義: int 

pthread_join

(pthread_t thread, void **retval);

描述 :

pthread_join()函式,以阻塞的方式等待thread指定的執行緒結束。當函式返回時,被等待執行緒的資源被收回。如果程序已經結束,那麼該函式會立即返回。並且thread指定的執行緒必須是joinable的。

引數 :

thread: 執行緒

識別符號,即執行緒id,標識唯一執行緒。

retval: 使用者定義的指標,用來儲存被等待執行緒的返回值。

返回值 : 0代表成功。 失敗,返回的則是錯誤號。

void pthread_exit(void* retval);

執行緒通過呼叫pthread_exit函式終止執行,就如同程序在結束時呼叫exit函式一樣。

這個函式的作用是,終止呼叫它的執行緒並返回乙個指向某個物件的指標。

執行緒建立pthread

執行緒建立函式 int pthread create pthread t restrict tidp 指向執行緒識別符號的指標 const pthread attr t restrict attr 設定執行緒屬性 void start rtn void 執行緒執行函式的起始位址 void restr...

pthread建立多執行緒

include include include include include include include include include include include tinyxml tinyxml.h include include include include define macxm...

pthread多執行緒的建立

多執行緒的建立 include include include include include include include include struct number void create void arg int main int argc,char argv sleep 2 return ...