復習中掌握線程的基本管理即可,而不用考慮線程的同步:
創建線程花費的代價,比創建進程小得多,所以同一個進程的,多個線程執行多個任務——>比多個進程執行多個任務更有效率。
線程也分為用戶級線程、內核級線程——對於前者,多個線程之間的上下文切換,由用戶決定;對於后者,則由系統決定。(二者一般是1:1或者1:n的對應關系)
多線程程序的編譯時,一定記得要加入動態庫,例如:gcc k.c -o k -lpthread,但運行時卻不用加。
首先#include <pthread.h>。
線程的創建:int pthread_create(&線程名字,NULL,線程執行函數名,傳遞的參數*arg),執行函數必須是這種:void *func(),可以帶參數,也可以不帶,函數體隨意。成功則返回0。
線程的等待(所謂等待,就是函數名稱的字面意思):int pthread_join(直接是線程名字,保存線程返回值的指針void **returnValue)。成功則返回0。
線程的退出:void pthread_exit(void *returnValue),返回值就是一個字符串,可以由其他函數,如等待函數pthread_join來檢測獲取其返回值。
//這是最簡單的使用了 #include <stdio.h> #include <pthread.h> void *func(void *arg) { printf("arg=%d\n", *(int *)arg); pthread_exit("bye bye"); } int main() { int res; pthread_t first_thread; int share_int = 10; res = pthread_create(&first_thread, NULL, func, (void *)&share_int); printf("res=%d\n", res); void *returnValue; res = pthread_join(first_thread, &returnValue); printf("returnValue=%s\n", (char *)returnValue); return 0; }
線程的屬性:
屬性創建:
屬性描述: