線程:相當於進程的一個執行流。一個進程可以有多個執行流,也就是說一個進程可以有多個線程。一個只有一個執行流的進程也可以看做線程。線程是操作系統調度和分派的基本單位。
雖然一個進程中的多個線程共享一份地址空間,但每個線程也有各自私有的資源,即每個線程即是相互聯繫的又相互獨立。
線程終止:
從線程函數return
線程函數調用pthread_exit();
調用函數pthread_cancel(pthread_t pthread);(可以在線程函數內部自己調用,也可以被其他同一進程的線程調用終止,但是結果不同)
線程ID可用 pthread_self()函數獲得。
線程分離:
線程可分爲可結合的和分離的,一般創建出的線程都是可結合的。可結合的線程可以被其他線程殺死和回收資源,但被回收前,其存儲器資源是不釋放的。要調用pthread_join()函數回收資源。分離線程不可以被其他線程殺死和回收資源,其存儲其資源在其終止時自動被系統回收。
可以用下面的函數將一個線程設置爲分離的,將線程設置爲分離的後,不可以再調用pthread_join()函數了。也就是說分離函數與pthread_join()函數是衝突的。
1 #include<stdio.h>
2 #include<pthread.h>
3 #include<stdlib.h>
4 void* thread1(void* arg)
5 {
6 int count =3;
7 while(count--)
8 {
9 printf("this is %d thread,%u\n",(int)arg,pthread_self());
10 sleep(1);
11 }
12 return (void*)3;
13 }
14 void* thread2(void* arg)
15 {
16 //pthread_detach(pthread_self()); //線程分離函數。
17 int count =3;
18 while(count--)
19 {
20 printf("this is %d thread,%u\n",(int)arg,pthread_self());
21 sleep(1);
22 }
23 pthread_exit((void*)4);
24 }
25 void* thread3(void* arg)
26 {
27 int count =3;
28 while(count--)
29 {
30 printf("this is %d thread,%u\n",(int)arg,pthread_self());
31 sleep(1);
32 }
33 }
34 int main()
35 {
36 pthread_t tid1,tid2,tid3;
37 pthread_create(&tid1,NULL,thread1,(void*)1); //創建線程
38 pthread_create(&tid2,NULL,thread2,(void*)2);
39 pthread_create(&tid3,NULL,thread3,(void*)3);
40 int count =5;
41 while(count--)
42 {
43 printf("this is main,%u\n",pthread_self());
44 sleep(1);
45 }
46 void *retval=NULL;
47 int res = pthread_join(tid1,&retval); //線程等待
48 if(res==0)
49 {
50 printf("pthread_join succeed,%d\n",(int)retval);
51 }
52 res = pthread_join(tid2,&retval);
53 if(res==0)
54 {
55 printf("pthread_join succeed,%d\n",(int)retval);
56 }
57 sleep(1);
58 pthread_cancel(tid3);
59 res = pthread_join(tid3,&retval);
60 if(res==0)
61 {
62 printf("pthread_join succeed,%d\n",(int)retval);
63 }
64 return 0;
65 }
結果:
[fbl@localhost thread]$ ./creat
this is main,3078321856
this is 2 thread,3067829104
this is 3 thread,3057339248
this is 1 thread,3078318960
this is main,3078321856
this is 2 thread,3067829104
this is 3 thread,3057339248
this is 1 thread,3078318960
this is main,3078321856
this is 2 thread,3067829104
this is 3 thread,3057339248
this is 1 thread,3078318960
this is main,3078321856
this is main,3078321856
pthread_join succeed,3
pthread_join succeed,4
pthread_join succeed,0
//將線程2設置爲分離的後,繼續調用pthread_join()函數
pthread_join succeed,3
pthread_join succeed,0
總結:
從上面代碼的執行結果來看:
當把函數設置爲分離的,在調用pthread_join()函數後會等待錯誤。