线程资源不释放结果会是怎么样?
代码如下:
[fy@localhost without_join]$ less main.c
#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <sched.h>
#include <errno.h>
void *consumer(void *p)
{
static a = 0;
a++;
printf("thread id %u ,total thread %d\n", (unsigned)pthread_self(), a);
pthread_exit(NULL);
}
int main(int argc, char *argv[])
{
pthread_t t1, t2, t3;
int ret;
while(1)
{
ret = pthread_create(&t1, NULL, consumer, NULL);
if(ret != 0)
{
printf("create failed,%d\n", ret);
exit(1);
}
};
sleep(1);
return 0;
}
部分运行结果:
thread id 71572368 ,total thread 287
thread id 61082512 ,total thread 288
thread id 50592656 ,total thread 289
thread id 40102800 ,total thread 290
thread id 29612944 ,total thread 291
thread id 19123088 ,total thread 292
thread id 3097111440 ,total thread 293
thread id 3107601296 ,total thread 294
thread id 3118091152 ,total thread 295
thread id 3128581008 ,total thread 296
thread id 3139070864 ,total thread 297
thread id 3149560720 ,total thread 298
thread id 3160050576 ,total thread 299
thread id 3170540432 ,total thread 300
create failed,11
[fy@localhost without_join]$
释放线程资源的形式有以下几种
1.初始化线程时,设置属性为可分离的
pthread_t thread;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
pthread_create(&thread,&attr,fun,arg);
2.使用pthread_join(pthread_t thread , void **value);与1互斥
3.使用pthread_detach(pthread_self());
线程资源不释放造成内存资源浪费,产生溢出,空间耗尽,程序卡死。