linux学习笔记16-多线程3

线程分离

 1. 如果不需要等待一个线程的返回值,可以将这个线程设置为分离状态,系统会在退出后自动回收该线程所占的资源.
 2. 在线程不能自己分离自己,只能由其他线程进行分离.
 3. 线程分离之后,不能在调用pthread_join.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>

void *func(void *arg)
{
	printf("thread print !\n");
	return NULL;
}

int main(int argc,char *argv[])
{
	pthread_t threadid;
	int ret = pthread_create(&threadid,NULL,func,NULL);
	if(ret != 0)
	{
		printf("create thread failed:%s\n",strerror(errno));
		return -1;
	}
	pthread_detach(threadid);  //在主线程分离threadid线程
	sleep(1);
	return 0;
}


秋风 2016-11-27