Linux下一个进程可以创建的最大线程数是多少?

如何(如果可能的话)修改这个值?


当前回答

取决于您的系统,只需编写一个示例程序[通过在循环中创建进程],并使用ps axo pid,ppid,rss,vsz,nlwp,cmd检查。当它不能再创建线程时,检查nlwp计数[nlwp是线程数],瞧,你得到了你的傻瓜证明的答案,而不是通过书籍

其他回答

使用nbio 非阻塞i / o 库之类的,如果你需要更多的线程来做I/O调用那个块

在实际应用中,限制通常由堆栈空间决定。如果每个线程获得1MB的堆栈(我不记得这是否是Linux上的默认值),那么32位系统将在3000个线程后耗尽地址空间(假设最后gb留给内核)。

但是,如果使用几十个以上的线程,您很可能会遇到糟糕的性能。迟早,您会得到太多的上下文切换开销、调度程序开销等等。(创建大量线程只会消耗大量内存。但是很多有实际工作要做的线程会减慢你的速度,因为它们在争夺可用的CPU时间)

你在做什么,这个极限甚至是相关的?

取决于您的系统,只需编写一个示例程序[通过在循环中创建进程],并使用ps axo pid,ppid,rss,vsz,nlwp,cmd检查。当它不能再创建线程时,检查nlwp计数[nlwp是线程数],瞧,你得到了你的傻瓜证明的答案,而不是通过书籍

可以通过以下命令查看当前值- 猫/proc/sys/kernel/threads-max

您还可以像这样设置值

Echo 100500 > /proc/sys/kernel/threads-max

您设置的值将根据可用的RAM页进行检查。如果线程结构占用可用RAM页面的1/8以上,则thread-max将相应降低。

Yes, to increase the threads number you need to increase the virtual memory or decrease the stack size. In Raspberry Pi I didn’t find a way to increase the virtual memory, if a decrease the stack size from default 8MB to 1MB It is possibly get more than 1000 threads per process but decrease the stack size with the “ulimit -s” command make this for all threads. So, my solution was use “pthread_t” instance “thread class” because the pthread_t let me set the stack size per each thread. Finally, I am available to archive more than 1000 threads per process in Raspberry Pi each one with 1MB of stack.