linux有創建線程的函數嗎

linux有創建線程的函數,即“pthread_create()”函數。該函數是類Unix操作系統中創建線程的函數,支持四個參數:參數1是指向線程標識符的指針、參數2用來設置線程屬性、參數3是線程運行函數的起始地址、參數4是運行函數的參數。

linux有創建線程的函數嗎

本教程操作環境:linux5.9.8系統、Dell G3電腦。

linux有創建線程的函數,那就是pthread_create()函數。

pthread_create()是類Unix操作系統(Unix、Linux、Mac OS X等)中創建線程的函數

頭文件

  #include

函數聲明

int?pthread_create( ????pthread_t?*restrict?tidp,???//新創建的線程ID指向的內存單元。 ????const?pthread_attr_t?*restrict?attr,??//線程屬性,默認為NULL ????void?*(*start_rtn)(void?*),?//新創建的線程從start_rtn函數的地址開始運行 ????void?*restrict?arg?//默認為NULL。上述函數需要參數,將參數放入結構中并將地址作為arg傳入。 ????);

返回值

  • 若成功則返回0,否則返回出錯編號

參數

  • 第一個參數為指向線程標識符的指針。

  • 第二個參數用來設置線程屬性。

  • 第三個參數是線程運行函數的地址。

  • 最后一個參數是運行函數的參數。

注意

  在編譯時注意加上-lpthread參數,以調用靜態鏈接庫。因為pthread并非Linux系統的默認庫。

函數用法

#include?<stdio.h> #include?<string.h> #include?<iostream> #include?<pthread.h> #include?<unistd.h> #include?<vector> #include?"main.h"  using?namespace?std;  struct?Sample?{ ????uint32_t?index; ????char?sex; ????uint32_t?age; ????uint32_t?result; };  void*?TaskEntry(void?*args) { ????Sample?*sa?=?(Sample*)args; ????uint32_t?num?=?sa-&gt;index; ????if?(num?==?0)?{ ????????printf("TaskEntry?entry?num?=?0n");??//?線程1執行體 ????????sleep(10); ????????printf("TaskEntry?entry?num?=?0?is?over!!!n"); ????}?else?if?(num?==?1)?{ ????????printf("TaskEntry?entry?num?=?1n");??//?線程2執行體 ????????sleep(10); ????????printf("TaskEntry?entry?num?=?1?is?over!!!n"); ????}?else?if?(num?==?2)?{ ????????printf("TaskEntry?entry?num?=?2n");??//?線程3執行體 ????????sleep(2); ????????printf("TaskEntry?entry?num?=?2?is?over!!!n"); ????} }  uint32_t?CreateTask(pthread_t&amp;?pid,?Sample&amp;?sample) { ????//?假設Sample.index?==?2創建任務失敗,直接返回 ????if?(sample.index?==?2)?{ ????????return?2; ????} ????pthread_attr_t??attr;??//?設置線程屬性 ????pthread_attr_init(&amp;attr); ????pthread_attr_setstacksize(&amp;attr,?64?*?1024);??//?設置線程棧大小為64KB ????uint32_t?ret?=?pthread_create(&amp;pid,?&amp;attr,?(void*(*)(void*))TaskEntry,?(void*)&amp;sample); ????if?(ret?!=?0)?{ ????????return?ret; ????} ????pthread_attr_destroy(&amp;attr);?//?取消線程的設置屬性 ????return?0; }  void?VerifyTask(vector<pthread_t>&amp;?taskID,?vector<sample>&amp;?taskArgs) { ????void?*ret; ????for?(int?index?=?0;?index?taskID(3); ????vector<sample>?taskArgs(3); ????for?(int?i?=?0;?i?<p id="注意編譯的使用需要加上編譯選項-lpthread比如g--lpthread-maincpp--o-main">注意編譯的使用需要加上編譯選項-lpthread,比如:g++ -lpthread main.cpp -o main</p> <p>相關推薦:《<a href="http://www.php.cn/course/list/33.html" target="_blank">Linux視頻教程</a>》</p></sample></sample></pthread_t></vector></unistd.h></pthread.h></iostream></string.h></stdio.h>

? 版權聲明
THE END
喜歡就支持一下吧
點贊5 分享