LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 2581|回复: 3

为何一个程序只能创建380个线程??

[复制链接]
发表于 2005-6-1 16:11:16 | 显示全部楼层 |阅读模式
系统:kernel2.6 nptl
[PHP]#include <stdio.h>
#include <pthread.h>

void *thread_routine(void *arg)
{
  // printf("hello world");
}

int  main(int argc,char *argv[])
{
  pthread_t thread_id;
  void *thread_result;
  int status;
  int i=0;
  int nsuss=0;
  for(i=0;i<500;i++)
    {
status=pthread_create(&thread_id,NULL,thread_routine,NULL);
  if(status != 0)
    {
      perror("create thread");
      return 0;
    }
  else
    {
      printf("create suss:%d",nsuss++);
    }
    }

  while(1)
    sleep(100);
}
[/PHP]
到380左右就出现Cannot allocate memory错误
是否是系统问题?
如何使其能创建上1k个线程?
谢谢了!
发表于 2005-6-1 16:13:48 | 显示全部楼层
线程堆栈太大,虚拟空间用完了!默认为10M,改到128K就足够了。
man pthread_attr_setstacksize
回复 支持 反对

使用道具 举报

发表于 2005-6-1 16:16:36 | 显示全部楼层
man里如果没有,自己到头文件里看看。
回复 支持 反对

使用道具 举报

发表于 2007-7-26 00:36:58 | 显示全部楼层
ulimit -a 看看stack size多大
ulimit -s 1024设置stack size大小,设成1024后大约可以开3000多个线程

用pthread_attr_setstacksize()函数设置是最方便的了!
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表