运行环境:linux,语言:C
pthread_detach()函数
1)含义:线程分离函数
2)返回值:成功返回0,非0失败。出现以下情况,pthread_detach()失败并将返回相应的值。
EINVAL:tid是分离线程
ESRCH:无法找到具有此ID的线程
3)函数作用:将线程标识的线程标记为分离。当一个分离的线程终止时,它的资源自动释放回系统,而不需要另一个线程与终止的线程连接。
4)应用场景:当我们不希望主函数等待子线程结束的时候,可以将线程设置为分离属性,通常让其处理耗时操作。在Qt中,经常用线程分离来防止界面假死。
测试程序:
#include <stdio.h>
#include <pthread.h>
void *mythread(void *arg)
{
printf("this is child thread...\n");
pthread_exit(NULL);
}
int main()
{
pthread_t thread;
if(pthread_create(&thread,NULL,mythread,NULL))
{
perror("create");
return -1;
}
pthread_detach(thread); //分离子线程
//sleep(1);
printf("this is main...\n");
return 0;
}
结果:
只输出 this is main...
如果加上延时注释,会先输出子线程的信息,再输出主函数的信息。