302

What is the maximum number of threads that can be created by a process under Linux?

How (if possible) can this value be modified?

18 Answers18

297

Linux doesn't have a separate threads per process limit, just a limit on the total number of processes on the system (threads are essentially just processes with a shared address space on Linux) which you can view like this:

cat /proc/sys/kernel/threads-max

The default is the number of memory pages/4. You can increase this like:

echo 100000 > /proc/sys/kernel/threads-max

There is also a limit on the number of processes (and hence threads) that a single user may create, see ulimit/getrlimit for details regarding these limits.

Shiva
  • 6,677
  • 4
  • 36
  • 61
Robert Gamble
  • 106,424
  • 25
  • 145
  • 137
  • 4
    The limit in /proc/sys/vm/max_map_count may limit the number of threads, too. It should be safe to increase that limit a lot if you hit it. – Mikko Rantalainen Jan 13 '12 at 11:50
  • 1
    Robert: Linux does implement per process limit indirectly. Check my answer for details ;) – codersofthedark Feb 09 '12 at 13:43
  • I am trying to change this on my ubuntu 12.04 and it not changing with your command. I also tried vi to change it, but I get `E667: Fsync failed` when I try to save on vi. – Siddharth May 04 '13 at 05:04
  • 4
    @dragosrsupercool the maximum thread are calculated using the total ram, no the virtual memory – c4f4t0r Nov 11 '13 at 19:39
  • 2
    The amount of stack size per thread (the default on your system) is more likely to be the limit than anything else. Reducing the per-thread stack size is a way to increase the total number of threads (although that's rarely a good idea). – Randy Howard Jan 23 '16 at 18:22
74

This is WRONG to say that LINUX doesn't have a separate threads per process limit.

Linux implements max number of threads per process indirectly!!

number of threads = total virtual memory / (stack size*1024*1024)

Thus, the number of threads per process can be increased by increasing total virtual memory or by decreasing stack size. But, decreasing stack size too much can lead to code failure due to stack overflow while max virtual memory is equals to the swap memory.

Check you machine:

Total Virtual Memory: ulimit -v (default is unlimited, thus you need to increase swap memory to increase this)

Total Stack Size: ulimit -s (default is 8Mb)

Command to increase these values:

ulimit -s newvalue

ulimit -v newvalue

*Replace new value with the value you want to put as limit.

References:

http://dustycodes.wordpress.com/2012/02/09/increasing-number-of-threads-per-process/

codersofthedark
  • 9,183
  • 8
  • 45
  • 70
  • 13
    Except 3 little details: 1. Linux doesn't do this, the presence of stacks and the fact that memory and address space are of finite size has nothing to do with it. 2. You have to specify a thread's stack when creating it, this is irrespective of `ulimit -s`. It is very well possible (not sensible, but possible) to create as many threads as there are possible thread IDs. Under 64 bit Linux, it is even easily "possible" to create more threads than there are thread IDs (of course it's not possible, but as far as stack goes, it is). 3. Stack reserve, commit and VM are different things, esp with OC. – Damon Jun 21 '13 at 18:42
  • 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 – Deulis Aug 02 '18 at 22:48
45

In practical terms, the limit is usually determined by stack space. If each thread gets a 1MB stack (I can't remember if that is the default on Linux), then you a 32-bit system will run out of address space after 3000 threads (assuming that the last gb is reserved to the kernel).

However, you'll most likely experience terrible performance if you use more than a few dozen threads. Sooner or later, you get too much context-switching overhead, too much overhead in the scheduler, and so on. (Creating a large number of threads does little more than eat a lot of memory. But a lot of threads with actual work to do is going to slow you down as they're fighting for the available CPU time)

What are you doing where this limit is even relevant?

jalf
  • 243,077
  • 51
  • 345
  • 550
  • 6
    1MB per thread for stack is pretty high, many programs don't need anywhere near this much stack space. The performance is going to be based on the number of *runnable* processes, not the number of threads that exist. I have a machine running right now with 1200+ threads with a load of 0.40. – Robert Gamble Dec 05 '08 at 16:21
  • 19
    the performance depends on what the the threads are doing. you can go much higher than a few dozen if they don't do much and hence less context-switching. – Corey Goldberg Mar 11 '09 at 14:09
  • stack is growing dynamically, only initial page is allocated off-the-bat – Michael Pankov Nov 04 '15 at 22:26
  • 2
    Downvote because of the "more than a few dozen threads". Either increase it, remove ir or back it up with sources. – dreua Nov 10 '21 at 10:21
38

proper 100k threads on linux:

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

2018 update from @Thomas, on systemd systems:

/etc/systemd/logind.conf: UserTasksMax=100000
Vladimir Kunschikov
  • 1,735
  • 1
  • 16
  • 16
  • 4
    Thank you, it finally allowed me to break through the 32k Java thread count. – berezovskyi Mar 11 '16 at 23:12
  • 1
    Doesn't work for me: $ ulimit -s 100000 $ ulimit -i 63645 $ cat /proc/sys/kernel/threads-max 127626 $ cat /proc/sys/vm/max_map_count 600000 $ cat /proc/sys/kernel/pid_max 200000 $ java -Xmx4G -Xss256k -cp . ThreadCreation ... 11542 11543 java.lang.OutOfMemoryError: unable to create new native thread at java.lang.Thread.start0(Native Method) at java.lang.Thread.start(Thread.java:717) at ThreadCreation.main(ThreadCreation.java:15) – Martin Vysny Nov 02 '17 at 08:17
  • @MartinVysny ulimit -s = thread size in kb. so you are trying to create threads with 100MB thread stack size. – Vladimir Kunschikov Nov 03 '17 at 10:09
  • added your suggestion without checking, @Thomas, thanks for the feedback anyway. – Vladimir Kunschikov Jan 16 '18 at 10:08
  • 2
    @VladimirKunschikov Thanks buddy, your solution really worked, and thanks Thomas to add that additional line, I can confirm it won't work with out that line. – Bill Hoo Aug 28 '18 at 06:22
17

@dragosrsupercool

Linux doesn't use the virtual memory to calculate the maximum of thread, but the physical ram installed on the system

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

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

kernel/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);

So thread max is different between every system, because the ram installed can be from different sizes, I know Linux doesn't need to increase the virtual memory, because on 32 bit we got 3 GB for user space and 1 GB for the kernel, on 64 bit we got 128 TB of virtual memory, that happen on Solaris, if you want increase the virtual memory you need to add swap space.

Delimitry
  • 2,987
  • 4
  • 30
  • 39
c4f4t0r
  • 1,563
  • 15
  • 24
14

To retrieve it:

cat /proc/sys/kernel/threads-max

To set it:

echo 123456789 | sudo tee -a /proc/sys/kernel/threads-max

123456789 = # of threads

slm
  • 15,396
  • 12
  • 109
  • 124
Vincent Van Den Berghe
  • 5,425
  • 2
  • 31
  • 40
  • I get permission denied when trying to write, even with root. – Kim Oct 17 '18 at 21:21
  • Well, it's been nearly a decade since this was posted. I'm not up to date on the current state of affairs, but a lot might have changed (and probably has)... – Vincent Van Den Berghe Oct 22 '18 at 17:46
  • 1
    issue with perm-deny may be append (`>`) part loses the `sudo`: try `echo 12345678 | sudo tee -a /proc/sys/kernel/threads-max` – dwanderson Jan 19 '20 at 00:07
10

Thread count limit:

$ cat /proc/sys/kernel/threads-max 

How it is calculated:

max_threads = mempages / (8 * THREAD_SIZE / PAGE_SIZE);

and: x86_64 page size (PAGE_SIZE) is 4K; Like all other architectures, x86_64 has a kernel stack for every active thread. These thread stacks are THREAD_SIZE (2*PAGE_SIZE) big;

for mempages :

cat /proc/zoneinfo | grep spanned | awk '{totalpages=totalpages+$2} END {print totalpages}';

so actually the number is not related with limitation of thread memory stack size (ulimit -s).

P.S: thread memory stack limitation is 10M in my rhel VM, and for 1.5G memory, this VM can only afford 150 threads?

Tombart
  • 30,520
  • 16
  • 123
  • 136
Albert Kong
  • 101
  • 1
  • 2
  • I have a 11 GB RAM Ubuntu 64 bit VM. threads-max is 95377 on my VM. But, going by the formula given by you, the max_threads is 204800. Why is the mismatch? Please clarify. Based on the formula given above, mempages is 3276799 – Mohan Oct 19 '22 at 07:41
6

For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.

This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf

Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.

Trent Lloyd
  • 1,832
  • 1
  • 15
  • 13
5

check the stack size per thread with ulimit, in my case Redhat Linux 2.6:

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

Each of your threads will get this amount of memory (10MB) assigned for it's stack. With a 32bit program and a maximum address space of 4GB, that is a maximum of only 4096MB / 10MB = 409 threads !!! Minus program code, minus heap-space will probably lead to an observed max. of 300 threads.

You should be able to raise this by compiling and running on 64bit or setting ulimit -s 8192 or even ulimit -s 4096. But if this is advisable is another discussion...

Axel Podehl
  • 4,034
  • 29
  • 41
4

It probably shouldn't matter. You are going to get much better performance designing your algorithm to use a fixed number of threads (eg, 4 or 8 if you have 4 or 8 processors). You can do this with work queues, asynchronous IO, or something like libevent.

twk
  • 16,760
  • 23
  • 73
  • 97
  • 4
    The purpose of multithreading is not only performance. For example you are listening 10 ports with a blocking system on 4 core processor. In this example there is no meaning of 4. – obayhan Apr 20 '17 at 14:12
3

Use nbio non-blocking i/o library or whatever, if you need more threads for doing I/O calls that block

Jérôme Verstrynge
  • 57,710
  • 92
  • 283
  • 453
wefeqfw
  • 39
  • 1
2

Depends on your system, just write a sample program [ by creating processes in a loop ] and check using ps axo pid,ppid,rss,vsz,nlwp,cmd. When it can no more create threads check nlwp count [ nlwp is the number threads ] voila you got your fool proof answer instead of going thru books

resultsway
  • 12,299
  • 7
  • 36
  • 43
2

To set permanently,

vim /etc/sysctl.conf

and add

kernel.threads-max = "value"
2

I think we missed another restriction which will also block the new thread creation, this is the kernel.pid_max limit.

root@myhost:~# lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.7 LTS
Release:    16.04
Codename:   xenial
root@myhost:~# uname -a
Linux myhost 4.4.0-190-generic #220-Ubuntu SMP Fri Aug 28 23:02:15 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

I find that at least in my system, this threshold kernel.pid_max is 32768. When I launch any simple JVM process, it reports error like below:

java/jstack/jstat ...
#
# There is insufficient memory for the Java Runtime Environment to continue.
# Cannot create GC thread. Out of system resources.
# An error report file with more information is saved as:
# /root/hs_err_pid1390.log

Check the memory, sufficient.

root@lascorehadoop-15a32:~# free -mh
              total        used        free      shared  buff/cache   available
Mem:           125G         11G         41G        1.2G         72G        111G
Swap:            0B          0B          0B

Check the system thread:

~# ps -eLf|wc -l
31506

But I check the system limit by ulimit:

root@myhost:~# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 515471
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 98000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 515471
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

From the ulimit output, we could see that currently thread number is far less than the maximum user process limit.

In fact, the limit which is reached is the kernel.pid_max

Very easy to check and tuning it: https://www.cyberciti.biz/tips/howto-linux-increase-pid-limits.html

wuchang
  • 3,003
  • 8
  • 42
  • 66
  • Interesting, I get `max user processes (-u) 2062175`, but the other day I tried to create 840 processes each of which create a few threads and I very quickly ran out of processes/threads... and I see that I have about 1100 processes but over 3700 tasks (a.k.a. threads). This is cool. I just don't understand how that works because I thought every single task was given a `pid_t` and those are limited to 65536 on my system. – Alexis Wilke Oct 10 '21 at 21:12
  • I don't see anything in the ulimit output mentioning threads – Joseph Garvin Jul 07 '22 at 17:59
1

We can see the maximum number of threads defined in the following file in linux

cat /proc/sys/kernel/threads-max

(OR)

sysctl -a | grep threads-max

0

You can see the current value by the following command- cat /proc/sys/kernel/threads-max

You can also set the value like

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

The value you set would be checked against the available RAM pages. If the thread structures occupies more than 1/8th) of the available RAM pages, thread-max would be reduced accordingly.

Arif
  • 331
  • 2
  • 7
0

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.

Deulis
  • 414
  • 4
  • 10
0

If you using Suse, you need to use one of these methods

https://www.suse.com/support/kb/doc/?id=000015901

global,

/etc/systemd/system.conf
    DefaultTasksMax=Value

For specific ssh service

/etc/systemd/system/sshd.service.d/override.conf
    TasksMax=Value
Mz A
  • 889
  • 11
  • 10