linux 多執行緒的學習

2021-06-18 04:25:48 字數 1869 閱讀 9027

pthread_exit

的乙個目標是,把乙個指標傳遞給

pthread_join函式

pthread_join

函式的思路是:通過引數的返回值,將該指標值返回給

pthread_join

的呼叫者

#include#include#includeusing namespace std;

void* thread(void* arg)

int main()

long *r;

pthread_join(tid, (void**)&r);

cout << r << endl;

cout << *r << endl;

cout << "in main thread, tid = " << pthread_self() << endl;

return 0;

}

上述**中,*r指向了乙個不再存在的物件,輸出結果為:

in thread, tid = 139814095632128

0x7f2901812e88

139814095632128

in main thread, tid = 139814112380736

long i = 2;

pthread_exit(&i);

改為pthread_exit(new long(2));

in thread, tid = 140514155718400

0x7fcbf80008c0

2in main thread, tid = 140514172467008

三:pthread_cancel的使用:

#include#include#includeusing namespace std;

void *thread(void *arg)

int main()

pthread_cancel(tid);

long *r;

pthread_join(tid, (void**)&r);

cout << pthread_canceled << endl;

cout << r << endl;

cout << "in main thread, tid = " << pthread_self() << endl;

return 0;

}

執行結果:

in thread, tid = 140456113821440

四:pthread_detach的使用: 若

pthread_join

比pthread_detach

先呼叫,也能獲取到退出資訊

#include#include#include#includeusing namespace std;

void *thread(void *arg)

int main()

int *r;

int s = pthread_join(tid, (void **)&r);

if(s == einval)

else

cout << "in main thread, tid = " << pthread_self() << endl;

return 0;

}

執行結果:

in thread, tid = 140355871602432

nihao

0in main thread, tid = 140355888351040

學習linux的多執行緒

xthread.h ifndef x thread h define x thread h include extern unsigned int xsleep unsigned int imillis class xthread endif xthread.cpp include void xth...

linux下的多執行緒學習

下面先來乙個例項來感受下linux下c語言多執行緒程式設計的樂趣!我們通過建立兩個執行緒來實現對乙個數的遞加。先不去理會 的含義,我們先執行linux,在其中編寫我們的第乙個c語言多執行緒程式。include include include include include define max 10...

linux多執行緒學習筆記

1.乙個程序中的所有執行緒都可以訪問該程序的組成部件,如檔案描述符和記憶體。2.在乙個程序中採用多執行緒程式設計可以改善響應時間和提高系統吞吐量。3.程序的所有資訊對該程序的所有執行緒都是共享的,包括可執行的程式文字,程式的全域性記憶體和堆記憶體,棧以及檔案描述符。4.執行緒id用pthread t...