C 多執行緒之建立多執行緒CreateThread

2021-07-22 01:18:28 字數 2253 閱讀 2152

#include
handle winapi createthread(

_in_opt_ lpsecurity_attributes lpthreadattributes,

_in_ size_t dwstacksize,

_in_ lpthread_start_routine lpstartaddress,

_in_opt_ lpvoid lpparameter,

_in_ dword dwcreationflags,

_out_opt_ lpdword lpthreadid

);

若執行緒建立成功,則返回執行緒控制代碼。

#include 

#include

using

namespace

std;

unsigned

long winapi fun(lpvoid lpparamter)

exitthread(-1);

}int main()

system("pause");

return

0;}

執行結果:

從列印的第一行看出來主線程main()執行到一半的時候,子執行緒fun開始執行,子執行緒執行到一半的時候,主線程又開始執行,這是因為主線程main()和子執行緒同時搶奪「螢幕」這一項資源導致的,cpu會輪流給這2個執行緒相同的時間片去執行自己的內容,時間到後切換到另乙個執行緒去執行,因此導致了這樣的結果。另外我們可以看到子執行緒的id為7920,目前這個id對我們貌似沒有什麼用。

#include
int pthread_create(pthread_t *tidp, const pthread_attr_t *attr,

(void*)(*start_rtn)(void*), void *arg);

tidp:第乙個引數為指向執行緒識別符號的指標。

attr:第二個引數用來設定執行緒屬性。

start_rtn:第三個引數是執行緒執行函式的起始位址。

arg:最後乙個引數是執行函式的引數。

-pthread

若執行緒建立成功,則返回0。若執行緒建立失敗,則返回出錯編號,並且*thread中的內容是未定義的;返回成功時,由tidp指向的記憶體單元被設定為新建立執行緒的執行緒id。

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

g++ -o example example.c -lpthread

#include 

#include

using

namespace

std;

static

const

int g_iruntime = 5000;

void* fun(void* ptr)

}int main()

sleep(1);

int iruntime = 0;

while(++iruntimecout

<< "main is running! "

<10000);

}sleep(1000);

return

0; }

這裡也造成了輸出空行的情況,也是由於「螢幕」資源爭奪造成。這裡多數一句,在linux下我使用了列印5000次的情況才勉強造成一次輸出空行,而windows平台下100行列印就能出現多次,感覺上linux對資源的分配比windows更加合理,造成衝突的機率也比windows低很多。

多執行緒之建立

建立執行緒的構造方法 1.thread 分配新的 thread 物件。2.thread runnable target 分配新的 thread 物件。3.thread string name 建立乙個執行緒,並給該執行緒物件分配乙個名字。4.thread runnable target,string...

Linux多執行緒之執行緒建立

1.函式 include intpthread create pthread t restrict thread,const pthread attr t restrict attr,void start routine void void restrict arg 引數 thread 為執行緒id...

C 多執行緒 建立執行緒

c 中線程的建立一般是通過std thread類實現的,具體的實現方式有以下幾種 void operator int a 過載括號運算子。如果無參則為void operator 這裡有兩種方法通過成員函式建立。而這兩種方法恰好也就是靜態成員函式和非靜態成員函式的區別。靜態成員函式與物件無關,只屬於類...