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

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


当前回答

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.

其他回答

linux上合适的100k线程:

ulimit -s  256
ulimit -i  120000
echo 120000 > /proc/sys/kernel/threads-max
echo 600000 > /proc/sys/vm/max_map_count
echo 200000 > /proc/sys/kernel/pid_max 

 ./100k-pthread-create-app

来自@Thomas的2018年更新,关于systemd系统:

/etc/systemd/logind.conf: UserTasksMax=100000

也许这并不重要。将算法设计为使用固定数量的线程(例如,如果有4或8个处理器,则使用4或8个线程),将获得更好的性能。您可以使用工作队列、异步IO或类似libevent的东西来实现这一点。

要永久地固定,

vim /etc/sysctl.conf

并添加

kernel.threads-max = "value"

使用ulimit检查每个线程的堆栈大小,在我的情况下Redhat Linux 2.6:

    ulimit -a
...
    stack size              (kbytes, -s) 10240

你的每个线程将得到这个数量的内存(10MB)分配给它的堆栈。一个32位的程序,最大地址空间为4GB,最大只有4096MB / 10MB = 409个线程!!减去程序代码,减去堆空间可能会导致观察到的最大值。300个线程。

您应该能够通过在64bit上编译和运行或设置ulimit -s 8192甚至ulimit -s 4096来引发这个问题。但如果这是明智的是另一个讨论…

@dragosrsupercool

Linux不使用虚拟内存来计算线程的最大值,而是使用安装在系统上的物理ram

 max_threads = totalram_pages / (8 * 8192 / 4096);

http://kavassalis.com/2011/03/linux-and-the-maximum-number-of-processes-threads/

内核/ fork.c

/* The default maximum number of threads is set to a safe
 * value: the thread structures can take up at most half
 * of memory.
 */
max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);

所以thread max在每个系统之间是不同的,因为安装的ram可以来自不同的大小,我知道Linux不需要增加虚拟内存,因为在32位上我们有3 GB的用户空间和1 GB的内核,在64位上我们有128 TB的虚拟内存,这发生在Solaris上,如果你想增加虚拟内存,你需要增加交换空间。