C 執行緒基礎

2021-07-23 20:37:16 字數 2721 閱讀 1801

執行緒可以說是輕型的程序

多執行緒共享程序的位址空間和資源使得執行緒的上下文切換優於程序

由於執行緒共享資源就會有搶占資源的情況主要的手段有 互斥鎖 ,條件變數 ,訊號量等等

簡單回顧下c++ 多執行緒

#include

pthread_create (thread,attr, start_routine, arg)

建立執行緒函式

#include #include #include using namespacestd;

#definenum_threads 5

void *printhello(void*threadid)

int main ()

}pthread_exit(null);

}

列印出來的結果:

main() :creating thread, 0

main() :creating thread, 1

main() :creating thread, 2

main() :creating thread, 3

main() :creating thread, 4

hello world!thread id, 4

hello world!thread id, 3

hello world!thread id, 2

hello world!thread id, 1

hello world!thread id, 0

如果我們注釋主線程pthread_exit 會發現其他執行緒函式不會執行 而是直接退出程序

main

執行緒終止時如果呼叫了

pthread_exit()

,那麼此時終止的只是

main

執行緒,而程序的資源會為其他由

main

執行緒建立的執行緒保持開啟的狀態,直到其他執行緒都終止。而在其他的由

main

執行緒建立的執行緒中

pthread_exit

並沒有這種作用。

如果我們去掉pthread_exit 在主函式裡面加入pthread_join(threads[i],&status);

主線程會等待其他執行緒結束之後再繼續執行

#include #include #include using namespacestd;

#definenum_threads 5

void *printhello(void*threadid)

int main ()

pthread_join(threads[i],&status);

}}

執行結果是這樣:

main() :creating thread, 0

hello world!thread id, 0

main() :creating thread, 1

hello world!thread id, 1

main() :creating thread, 2

hello world!thread id, 2

main() :creating thread, 3

hello world!thread id, 3

main() :creating thread, 4

hello world!thread id, 4

主線程等待其他執行緒結束後繼續執行

是不是很好理解了 我們再改一下

pthread_attr_init(&attr); // 初始化pthread_attr_t

pthread_attr_setdetachstate(&attr,pthread_create_joinable);  //設定執行緒屬性

#include #include #include using namespacestd;

#definenum_threads 5

void *printhello(void*threadid)

int main ()

}pthread_attr_destroy(&attr);

for( i=0; i < num_threads; i++ ){

pthread_join(threads[i],&status); // 主線程走到這裡等待其他執行緒執行完畢

cout<<"hellothread : "<

main() : creating thread, 0

main() :creating thread, 1

main() :creating thread, 2

main() :creating thread, 3

main() :creating thread, 4

hello world!thread id, 4

hello world!thread id, 3

hello world!thread id, 2

hello world!thread id, 1

hello world!thread id, 0

main() hellothread : 0

main() hellothread : 1

main() hellothread : 2

main() hellothread : 3

main() hellothread : 4

c 執行緒基礎

程序 process 是引用程式的例項要使用的資源的乙個集合 程序就是一種資源,是應用程式所用的資源,乙個exe就是乙個程序 每個程序都被賦予了乙個虛擬位址空間,每個應用程式都在各自的程序中執行來確保應用程式不受其他應用程式的影響,程序是作業系統為我們提供的一種保護應用程式的一種機制。執行緒 thr...

C 執行緒運用基礎

threadstart ts new threadstart a.f threadstart 是乙個委託,用以關聯a.f方法 thread th new thread ts thread是乙個類,例項化物件時呼叫的構造函式引數為ts這個委託物件 th.start 執行緒開始 執行緒的同步控制 1.使...

c語言基礎 執行緒

在標頭檔案 threads.h 中,定義和宣告了支援多執行緒的巨集 型別和函式。所有直接與執行緒相關的識別符號,均以字首 thrd 作為開頭。例如,thrd t 是乙個物件型別,它標識了乙個執行緒。建立並開始執行乙個新執行緒thrd create int thrd create thrd t thr...