#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<unistd.h>
#include <pthread.h>
void *mythread(void *arg)
{
printf("id==[%ld]\n",pthread_self());
}
int main()
{
//定义pthread_attr_t类型的变量
pthread_attr_t attr;
//初始化attr变量
pthread_attr_init(&attr);
//设置attr为分离属性
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
//int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
// void *(*start_routine) (void *), void *arg);
pthread_t thread;
int ret=pthread_create(&thread,&attr,mythread,NULL);
if(ret!=0)
{
printf("pthread_create error:[%s]\n",strerror(ret));
return -1;
}
//验证子线程是否为分离状态,如果是分离状态,pthread_join不会阻塞,立即打印错误
ret=pthread_join(thread,NULL);
if(ret!=0)
{
printf("prhread_join error:[%s]\n",strerror(ret));
}
printf("father thread id==[%ld]\n",pthread_self());
//释放线程属性
pthread_attr_destroy(&attr);
//防止主线程结束,子线程还没有执行
sleep(1);
}
结果: