在不终止整个进程的前提下,单个线程可通过pthread_exit退出,它的定义:
#include <pthread.h> void pthread_exit(void *rval_ptr)
参数rval_ptr无类型指针,与创建线程最后一个参数传给子线程的参数类型一致,其它线程可以通过pthread_join访问这个指针
#include <pthread.h> int pthread_join(pthread_t thread, void **rval_ptr);
其它线程调用pthread_join之后,就会一直阻塞起来,直到第一个参数指定的线程调用pthread_exit之后,才会返回,返回码传给pthread_join的第二个参数rval_ptr;假如对返回码没兴趣,调用pthread_join的时候,第二个参数直接设置为NULL,那么只会阻塞等待指定的线程终止,而不会获取返回状态
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void *thread(){
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("Child: pid %d, tid %u\n", pid, tid);
pthread_exit("Hello, lihui!");
}
int main(){
pid_t main_pid;
pthread_t main_tid, child_tid;
void *status;
if (pthread_create(&child_tid, NULL, thread, NULL)){
printf("Create child thread failed!\n");
exit(1);
}
main_pid = getpid();
main_tid = pthread_self();
printf("Main: pid %d, tid %u\n", main_pid, main_tid);
if (pthread_join(child_tid, &status)){
printf("Cannot join child thread!\n");
exit(1);
}
printf("Child thread exit with code: %s\n", (char *)status);
return 0;
}
编译执行一下:
[lihui@localhost ~]$ ./a.out Main: pid 7984, tid 1167918848 Child: pid 7984, tid 1167910656 Child thread exit with code: Hello, lihui!
