Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4733327
  • 博文数量: 930
  • 博客积分: 12070
  • 博客等级: 上将
  • 技术积分: 11448
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-15 16:57
文章分类

全部博文(930)

文章存档

2011年(60)

2010年(220)

2009年(371)

2008年(279)

分类: LINUX

2010-05-06 21:36:31

线程应用程序最常见导致创建线程失败的原因是线程栈大小的设置。创建一个新的线程,默认情况下系统为线程栈预留了2MB的寻址空间。线程栈起始于进程虚拟内存的高端地址,并向虚拟内存底端地址方向扩展。取决于线程本身的大小以及其它线程内存分配的情况,进程虚拟地址空间消耗过快可能导致创建线程失败。

这里有一个测试程序可以看到,Linux下最多可以创建多少个线程。

#include

#include

#include

 

void *ThreadFunc()

{

    static int count = 1;

    printf ("Create thread %d\n", count);

    pthread_detach (pthread_self());

    count++;

   

}

 

main(void)

{

    int     err;

    pthread_t tid;

    while (1){

           err = pthread_create(&tid, NULL, ThreadFunc, NULL);

           if (err != 0){

               printf("can't create thread: %s\n", strerror(err));

           break;

           

    }

}

 

输出结果如下:

Create thread 301

Create thread 302

can't create thread: Cannot allocate memory

用 ulimit -s 可以查看到栈的默认大小为10240K

32位linux下的进程用户空间是3072M, 3072/10.24=300。为什么实际会比计算出来的多2个,这个原因还不太清楚。

可以在调用 pthread_create 的时候用 pthread_attr_getstacksize 设置栈的大小,或者直接用 ulimit -s 设置栈的大小。

如果修改上面的测试代码为

#include

#include

#include

 

void *ThreadFunc()

{

    static int count = 1;

    printf ("Create thread %d\n", count);

    pthread_detach (pthread_self());

    count++;

   

}

 

main(void)

{

    int     err;

    pthread_t tid;

    while (1){

           err = pthread_create(&tid, NULL, ThreadFunc, NULL);

           if (err != 0){

               printf("can't create thread: %s\n", strerror(err));

           break;

           

    }

}

那么得到的结果将是:

Create thread 560000

Create thread 560001

……………

这里用到了pthread_detach (pthread_self())来释放线程所占用的内存资源(线程内核对象和线程堆栈)。这样就可以创建更多的线程,而不会出现Cannot allocate memory的错误。

阅读(2030) | 评论(1) | 转发(0) |
给主人留下些什么吧!~~

chinaunix网友2010-05-31 22:32:57

MBT is based on Africa's indigenous people to create innovative walking barefoot, and wear this shoe can stimulate the body to relax the muscles so that the muscles of heat to be released, consumed calories, thus to achieve weight loss results. MBT's pursuit of beauty in order to satisfy customers, design a variety of styles, such as Mbt Chapa shoe, MBT Lami Shoe