參考:大丙老師線程
1.個數控制

2.創建線程

3.編譯的時候需要注意:

4.線程退出
子線程是在主線程中創建的,因此主線程退出之后子線程也就結束運行,但是子線程的結束不影響主線程的的運行。

如下的示例,子線程並不會在終端打印出id信息,因為主線程運行結束之后就退出了並且釋放了地址空間,因此子線程也無法運行了。
#include<pthread.h> #include<stdio.h> #include<stdlib.h> void* callback(void* arg); int main(){ pthread_t tid; pthread_create(&tid,NULL,callback,NULL); printf("main thread d:%ld\n",pthread_self()); } void* callback(void* arg){ printf("sun thread d:%ld\n",pthread_self()); return NULL; }
因此主線程的退出需要調用退出函數保證子線程還能正常運行,修改一下主線程(main函數)。
int main(){ pthread_t tid; pthread_create(&tid,NULL,callback,NULL); printf("main thread d:%ld\n",pthread_self()); pthread_exit(NULL); }
5.線程回收:主線程回收子線程的內核資源

代碼如下:
#include<pthread.h> #include<stdio.h> #include<stdlib.h> struct ThInfo{ int num; int age; }; void* callback(void* arg); int main(){ pthread_t tid; pthread_create(&tid,NULL,callback,NULL); printf("main thread d:%ld\n",pthread_self()); void* arg; pthread_join(tid,&arg); struct ThInfo* info=(struct ThInfo*)arg; printf("sub thread age:%d,num:%d\n",info->age,info->num); } void* callback(void* arg){ struct ThInfo info; info.age=9; info.num=100; printf("sun thread d:%ld\n",pthread_self()); pthread_exit(&info); return NULL; }
運行結果如下:

子線程的回收參數不正確,是因為主線程退出時將棧的地址空間釋放掉了,而子線程的臨時變量也是放置在同一塊空間中的,因此被釋放掉之后就被其他值覆蓋了。
解決方案:
(1)將callback中的結構體變量ThInfo indo設置為全局變量,這樣就被放置在全局區,主線程中即可在全局區訪問到正確的數值;
(2)callback中的結構體變量ThInfo indo在main函數中聲明,相當於在棧中分配了一塊空間用於接受保存子線程退出時的參數,將其地址傳遞給callback,callback將需要返回的結果寫在這個空間中;
注意:指針與地址會有相應變化;
int main(){ pthread_t tid; struct ThInfo *info; pthread_create(&tid,NULL,callback,info); printf("main thread d:%ld\n",pthread_self()); void* arg; pthread_join(tid,&arg); info=(struct ThInfo*)arg; printf("sub thread age:%d,num:%d\n",info->age,info->num); } void* callback(void* arg){ struct ThInfo* info=(struct ThInfo*)arg; info->age=9; info->num=100; printf("sun thread d:%ld\n",pthread_self()); pthread_exit(info); return NULL; }
6.線程分離

子線程退出的時候,內核資源由其他進程接管回收,因此不需要主線程回收,也就不需要調用pthread_join()了,進而不會阻塞主進程。
int main(){ pthread_t tid; pthread_create(&tid,NULL,callback,NULL); pthread_detach(tid); pthread_exit(NULL); }
7.線程取消

第一步好理解,就是在A線程中調用pthread_cancel;

第二步的意思是,A中調用取消函數時並不會立刻結束B線程,而是要等到B中有系統調用的過程才會結束,比如調用printf系統調用,那么B就會結束。
