(转载)Linux系统中分离线程的使用

(转载)http://hi.baidu.com/gropefor/item/da814aaadfbd53f215329bb6

摘要:本文简要介绍了LINUX多线程编程中分离线程的概念并给出了使用pthread库时需要用到分离线程

的程序实例。

关键字:分离线程,detach,pthread_create,pthread_detach,ENOMEM,12

            线程一般有分离非分离两种状态。默认的情形下是非分离状态,父线程维护子线程的某些信息并

等待子线程的结束,在没有显示调用join的情形下,子线程结束时,父线程维护的信息可能没有得到及时释

放,如果父线程中大量创建非分离状态的子线程(在LINUX系统中使用pthread_create函数),可能会产生表

示出错的返回值12,即ENOMEM(在errno.h中定义),表示栈空间不足。而对分离线程来说,不会有其他的

线程等待它的结束,它运行结束后,线程终止,资源及时释放。

      为了防止pthread_create线程是出现返回值12(即ENOMEM)的错误,建议以如下的方式

创建分离状态的线程!

#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

//线程入口函数
void *func(void *arg)
{
    int i = *(int *)(arg);
    printf("I'am worker:%d\n",i); 
}

int main()
{
  pthread_t tid; //线程id //创建大量线程 int count = 10000;//多次循环 for(int j=0 ; j < count ; ++j) { //线程参数 int * p = new int(j); //创建线程 int ret= pthread_create(&tid, NULL, func, (void*)p); if( ret )//创建失败 { printf("create thread error:%d\n",ret); } else//创建成功 { //分离线程回收线程的stack占用的内存 pthread_detach(tid); } } return 0; }
原文地址:https://www.cnblogs.com/Robotke1/p/3053891.html