—-介绍——
*
在任何一个时间点上,线程都是可分离或者可结合的。一个可结合的线程能够被其它线程收回其资源和杀
死。在其他线程回收之前,他的存储器资源(例如栈)是不释放的。相反,一个分离的线程是不能被其他
线程回收或者杀死,他的存储器资源在它终止时系统自动释放。
* 创建线程函数原型 :int pthread_create(pthread_t *thread, const pthread_attr_t
* attr, void *(*start_routine) (void *), void *arg);
* 分离线程函数原型 : int pthread_detach(pthread_t thread)
* 等待线程函数原型: int pthread_join(pthread_t thread, void **retval);
*
* 1. 分离线程的情况 : 线程可以自己调用分离函数来分离自己,也可被别的线程调用分离函数从而
* 分离线程,线程分离后,就代表没有任何其它的线程可以使用pthread_join() 来等待它。
*
* 2. 默认情况下,线程被创建成可结合的。每个可结合线程都应该被显示的回收,即通过调用
* pthread_join();
—– 注意&备注:—–
一 . 等待线程的第二个参数属于创建线程的函数的返回值的&再强制类型转换为
void**。
二 . 其中自己使自己分离有一些注意事项:对于新线程来说,自己已经是分离状态了
,但对于主线程来说,主线程不清楚新线程是否是分离状态,所以当我分别在两天centos操作系统的机子
上在主线程用 “已分离的线程无法通过使用pthread_join()等待该线程”进行 验证的时候,出现了两种
情况:一种是,主线程等待新线程执行结束,主线程再结束,另一种是直接返回错误信息。
:结论:当你想要使某个线程变成可分离状态的时候,最好不要线程自己分离自己。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>
void* thread_run(void *argc)
{
//自己使自己分离
//pthread_detach(pthread_self());
/*这里我的程序的执行结果是主线程等待新线程结束后执行。并没有返回"无法调用
pthread_join()"错误信息:所以就和备注里面说的一样:主线程不清楚新线程是否分离*/
int count = 0;
while(1)
{
sleep(1);
printf("this is a new thread! %lu\n",pthread_self());
if(count == 5)
{
break;
}
count++;
}
printf("new thread done\n");
return (void*)23;
}
int main()
{
pthread_t tid;
int nu = pthread_create(&tid,NULL,thread_run,NULL);
if(nu != 0)
{
printf("%s\n",strerror(nu));
return 0;
}
/*调用pthread_join()后,若该线程没有运行结束,则调用者会被阻塞,一直等待新线程结束,
调用者才会继续运行*/
//新线程已经设置为分离状态,则线程结束运行时会自动释放所有资源,而无需被等待
int exitCode;
pthread_detach(tid); //使得新线程分离
int errorCode = pthread_join(tid,(void**)&exitCode);
if( errorCode != 0)
{
printf("exitCode: %d\n",exitCode);
printf("无法使用pthread_join(): error : %s \n",strerror(errorCode));
return errorCode;
} //这种情况,函数在执行到该位置时,输出错误信息
while(1)
{
sleep(1);
printf("this is a main thread ! :%lu\n ",pthread_self());
}
return 0;
}
程序结果截图:
已经分离的新线程 当主线程中调用pthread_detach():
已经分离的新线程 在自己的线程中调用pthread_detach():