pthread_detach
- 头文件:#include(pthread.h)
- 原型:int pthread_detach(pthread_t thread);
- 返回值:成功返回0;失败返回错误号
- 作用:线程分离,线程主动与主控线程断开关系,线程结束后,主动释放资源
也可用pthread_create()函数中参数二设置
1 #include<stdio.h>
2 #include<pthread.h>
3 #include<unistd.h>
4 #include<string.h>
5 void *th_funct(void *arg)
6 {
7 int *i;
8 int *retval=arg;//赋予retval指针值
9 i=(int *)arg;
10 printf("my_pthread_num=%lu and num=%d\n",pthread_self(),*i);
11 sleep(1);
12 pthread_exit((void *)retval);//将指针转化为void指针类型,退出并保留信息
13 }
14 void main(void)
15 {
16 pthread_t tid;
17 int ret;
18 int *retval;
19 int *i;
20 int log=1;
21 i=&log;
22 pthread_create(&tid,NULL,th_funct,(void *)i);
23 pthread_detach(tid);//线程分离
24 sleep(2);
25 ret=pthread_join(tid,(void **)&retval);//回收线程资源且将eixt的信息写到retval地址上
26 if(ret!=0){
27 printf("join error:%s\n",strerror(ret));
28 }
29 printf("%d\n",*retval);//打印退出时的状态信息
30 }