max_threads = totalram_pages / (8 * THREAD_SIZE / PAGE_SIZE);
(defined in kernel/fork.c, called by init/main.c)
PAGE_SIZE is architecture specific, for x86 it’s 4kb (and 4MB but thats a discussion for another day), and is calculated via:
#define __AC(X,Y) (X##Y)
#define _AC(X,Y) __AC(X,Y)
#define PAGE_SHIFT 12
#define PAGE_SIZE (_AC(1,UL) << PAGE_SHIFT)
PAGE_SHIFT is a constant for x86, other architectures support
alternate (larger) page sizes. THREAD_SIZE is also architecture
specific:
#define THREAD_ORDER 1
#define THREAD_SIZE (PAGE_SIZE << THREAD_ORDER)
THREAD_ORDER is 1 in x86, but can vary depending on the arch. These
result in a PAGE_SIZE of 4096 and a THREAD_SIZE of 8192 for x86. Back to
the formula above, we can fill it in as:
max_threads = totalram_pages / (8 * 8192 / 4096);
becomes
max_threads = totalram_pages / 16 ;
Calculating totalram_pages is a bit tricky since its not just the
full system ram allocated to pages. The easiest way to calculate it from
/proc/zoneinfo, by summing the spanned pages:
cat /proc/zoneinfo | grep spanned | awk ‘{totalpages=totalpages+$2} END {print totalpages}’
3407872
So on my PC with 12 gigabytes of memory we’ve got:
max_threads = 3407872 / 16;
becomes
max_threads = 212992;
Now the default maximum number of threads is designed to be able to
only consume half the memory from threads alone. But one user should
also not be able to consume all of the threads on the system. Back in
kernel/fork.c we have:
init_task.signal->rlim[RLIMIT_NPROC].rlim_cur = max_threads/2;
init_task.signal->rlim[RLIMIT_NPROC].rlim_max = max_threads/2;
So there you have it.
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
It looks like you're new here. If you want to get involved, click one of these buttons!