1 #include <pthread.h> 2 #include <stdlib.h> 3 #include <stdio.h> 4 #include <unistd.h> 5 void *th_fn(void *arg) 6 { 7 printf("new thread 0\n"); 8 return (void *)1; 9 } 10 11 void *th_fn1(void *arg) 12 { 13 printf("new thread 1\n"); 14 pthread_exit((void *)2); 15 } 16 17 void *th_fn2(void *arg) 18 { 19 while(1) { 20 printf("new thread 2\n"); 21 sleep(1); 22 } 23 } 24 25 int main() 26 { 27 pthread_t ptid; 28 void *tret; 29 pthread_create(&ptid, NULL,th_fn ,NULL); 30 //获取线程退出的状态 31 pthread_join(ptid, &tret); 32 printf("code 0 exit id = %d\n", (int)tret); 33 34 pthread_create(&ptid, NULL,th_fn1 ,NULL); 35 pthread_join(ptid, &tret); 36 printf("code 1 exit id = %d\n", (int)tret); 37 38 pthread_create(&ptid, NULL,th_fn2 ,NULL); 39 sleep(3); 40 pthread_cancel(ptid); 41 pthread_join(ptid, &tret); 42 printf("code 2 exit id = %d\n", (int)tret); 43 44 return 1; 45 }
编译:
gcc pthread_join.c -lpthread -o pthread_join
输出:

                    
                
                
            
        
浙公网安备 33010602011771号