标签:
1 #include <pthread.h> 2 #include <unistd.h> 3 #include <stdio.h> 4 #include <stdlib.h> 5 #include <string.h> 6 #include <error.h> 7 8 void *thr_fn1(void *arg) 9 { 10 printf("thread 1 returning\n"); 11 return((void *)1); 12 } 13 14 15 void *thr_fn2(void *arg) 16 { 17 printf("thread 2 exiting\n"); 18 pthread_exit((void *)2); 19 } 20 21 int main(void) 22 { 23 int err; 24 pthread_t tid1,tid2; 25 void *tret; 26 27 err=pthread_create(&tid1,NULL,thr_fn1,NULL);//创建线程1 28 if(err!=0) 29 fprintf(stderr, "errno: %s", strerror(err));//创建线程2 30 err=pthread_create(&tid2,NULL,thr_fn2,NULL); 31 if(err!=0) 32 fprintf(stderr, "errno: %s", strerror(err)); 33 err=pthread_join(tid1,&tret);//接收线程1的返回值 34 if(err!=0) 35 fprintf(stderr, "errno: %s", strerror(err)); 36 printf("thread 1 exit code %d\n",(int)tret); 37 38 err=pthread_join(tid2,&tret);//接收线程2的返回值 39 if(err!=0) 40 fprintf(stderr, "errno: %s", strerror(err)); 41 printf("thread 2 exit code %d\n",(int)tret); 42 exit(0); 43 }
程序编译及运行:
1 gcc -o pthread pthread.c -lpthread 2 thread 2 exiting 3 thread 1 returning 4 thread 1 exit code 1 5 thread 2 exit code 2
标签:
原文地址:http://www.cnblogs.com/wireless-dragon/p/5189108.html