线程终止

来源:互联网 发布:红色衣服知乎 编辑:程序博客网 时间:2024/04/28 23:13
#include <pthread.h>#include <stdio.h>#include <stdlib.h>void* thr_fn1( void * arg ){printf( "thread 1 returning\n" );return (void *)100s;}void * thr_fn2( void *arg ){printf( "thread 2 returning\n" );return (void *)12;}int main(void){interr;pthread_ttid1, tid2;void*rval_ptr;err = pthread_create( &tid1, NULL, thr_fn1, NULL );if( err != 0 )printf( "can't create thread tid1\n" );err = pthread_create( &tid2, NULL, thr_fn2, NULL );if( err != 0 )printf( "can't create thread tid2\n" );err = pthread_join( tid1,  &rval_ptr);if( err != 0 )printf( "pthread_join tid1 error\n" );printf( "thread 1 exit code %d \n" ,(int )rval_ptr);err = pthread_join( tid2, &rval_ptr );if( err != 0 )printf( "pthread_join tid2 error\n" );printf( "thread 2 exit code %d\n", (int)rval_ptr );exit( 0 );}

 

 

该函数的运行结果如下所示:

wangkai@ubuntu:~/Test$ cc -lpthread pthread.c wangkai@ubuntu:~/Test$ ./a.out thread 1 returningthread 1 exit code 100 thread 2 returningthread 2 exit code 12wangkai@ubuntu:~/Test$ ./a.out thread 1 returningthread 1 exit code 100 thread 2 returningthread 2 exit code 12wangkai@ubuntu:~/Test$ ./a.out thread 2 returningthread 1 returningthread 1 exit code 100 thread 2 exit code 12wangkai@ubuntu:~/Test$ cc -lpthread pthread.c wangkai@ubuntu:~/Test$ ./a.out thread 1 returningthread 1 exit code 100 thread 2 returningthread 2 exit code 12wangkai@ubuntu:~/Test$ 


当一个线程通过调用pthread_exit退出或者简单的从启动例程中返回时,进程中的其他线程可以通过调用pthread_join函数获得该线程的退出状态。