//以下程序在linux 系统亲测通过
//gcc detachstate_pthread.c -o detachstate_pthread -lpthread
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
void thread_routine (void)
{
int i =0;
for(i=0;i<10;i++)
{
printf(" i :%d \n",i);
sleep(2);
}
pthread_exit("");
}
void thread_routine_one (void)
{
int i =0;
for(i=0;i<15;i++)
{
printf("ii: %d \n",i);
sleep(2);
}
pthread_exit("");
}
int main (int argc, char *argv[])
{
pthread_t thread_id ,thread_id2;
void *thread_result;
int status;
//创建成功返回0 //并开始运行 thread_routine
status = pthread_create (&thread_id, NULL, (void *)thread_routine, NULL);
if (status == 0)
{
printf("Create thread %d\n",thread_id);
}
status = pthread_create (&thread_id2, NULL, (void *)thread_routine_one, NULL);
if (status == 0)
{
printf("Create thread %d\n",thread_id2);
}
//正常状态:可以由其他线程终止,回收资源。(可以看成有人等,有人陪)
//分离状态:不能被其他线程终止,存储资源在它终止时由系统自动回收释放。(没人等,没人陪,自生自灭,死后回归大自然)
//设置为分离线程 //这是创建成功后设置为分离线程 //还有一种创建的时候就设置为分离状态
pthread_detach(thread_id);
pthread_detach(thread_id2);
//另一种创建分离线程的方向 在下面
printf("不需要等待了,直接运行");
sleep(10);
return 0;
}
/*
创建 detach 线程的另外一种方式:
pthread_t tid;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_create(&tid, &attr, THREAD_FUNCTION, arg);
总之为了在使用 pthread 时避免线程的资源在线程结束时不能得到正确释放,
从而避免产生潜在的内存泄漏问题,在对待线程结束时,要确保该线程处于 detached 状态,
否着就需要调用 pthread_join() 函数来对其进行资源回收。
*/
学习《POSIX多线程程序设计》笔记一(分离线程)
最新推荐文章于 2020-11-17 18:40:58 发布