连接线程
#include"string.h" #include"stdio.h" #include"stdlib.h" #include"pthread.h" void *thread_fun1(void *arg) { printf("i am thread 1\n"); return (void *)1; } void *thread_fun2(void *arg) { printf("i am thread 2\n"); pthread_detach(pthread_self());//用于分离线程,成功返回0,失败返回错误码 pthread_exit((void *)2); } int main() { int err1,err2; pthread_t tid1, tid2; void *rval1, *rval2; err1 = pthread_create(&tid1, NULL, thread_fun1, NULL); err2 = pthread_create(&tid2, NULL, thread_fun2, NULL); if(err1 || err2) { printf("create new thread failed\n"); return 0; } printf("i am main thread\n"); printf("join1 rval is %d\n",pthread_join(tid1, &rval1)); printf("join2 rval is %d\n",pthread_join(tid2, &rval2));//连接成功返回0,否则返回错误码 printf("thread1 err code is %d\n",(int *)rval1); printf("thread2 err code id %d\n",(int *)rval2); printf("i am main thread\n"); return 0; }
i am main thread
i am thread 2
i am thread 1
join1 rval is 0    //成功
join2 rval is 22     //失败,已经分离了,连接的话就会错误
thread1 err code is 1        
thread2 err code id -1216909312
i am main thread
。
 
                    
                     
                    
                 
                    
                 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号