一、线程的连接与分离
线程分为分离线程和非分离线程,分离线程退出时会释放它的资源,非分离线程退出时,不会释放资源,需要另一个线程为它调用pthread_join函数或者进程退出时才会释放资源,只有非分离线程才是可连接的,线程一旦设置为PTHREAD_CREATE_DETACH状态(不论是创建时设置还是运行时设置)则不能再恢复到PTHREAD_CREATE_JOINABLE状态。
二、相关函数
函数原型 | 作用 |
int pthread_detach(pthread_t thread) | 将非分离线程设置为分离线程,参数thread是要分离的线程ID |
int pthread_deteach( pthread_self() ) | 将自身线程设置为分离线程,成功返回0,失败返回非0错误码 |
int pthread_join(pthread_t thread,void **retval) | 用于将调用线程挂起,知道参数thread所指线程终止运行位置 |
retval为thread所指线程返回的值,为NULL或其他值 |
三、编程练习
创建两个线程thread1、thread2,thread1打印5次"I am thread1!"后退出线程,并返回i的值;thread2调用pthread_join()函数获取thread1的返回值并打印,之后打印5次"I am thread2!"并退出。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
pthread_t thread1,thread2;
//线程的分离
void *pthread1_func(void * pra)
{
int i = 0;
while( (i++) < 5 )
{
printf("I am thread1!\r\n");
sleep(1);
}
pthread_exit((void*)i);
}
void *pthread2_func(void * pra)
{
int rc,i = 0;
void *retval;
rc = pthread_join(thread1, &retval); /*等待线程1终止,并获取返回值*/
printf("The data received from thread1 is %d\r\n",(void *)retval);
if (rc)
{
printf("ERROR; return code from pthread_join() is %d\n", rc);
exit(-1);
}
while( (i++) < 5 )
{
printf("I am thread2!\r\n");
sleep(1);
}
pthread_exit(NULL);
}
int main(void)
{
int res;
res = pthread_create(&thread1,NULL,pthread1_func,NULL);
if(res)
{
printf("thread1 create fail\r\n");
exit(-1);
}
res = pthread_create(&thread2,NULL,pthread2_func,NULL);
if(res)
{
printf("thread2 create fail\r\n");
exit(-1);
}
pthread_exit(NULL);
return 0;
}
运行结果: