I remember I typed "./client localhost & ./client localhost & ...." for repeating over 500+ times , in testing some network program.
And when I met some kind of stuck in the program, I got the error Resource temporarily unavailable, then can't start more client to test.
Even more, I can't even start a console terminator.
Here come the explanation :
"
Linux系統中每個線程都擁有獨立的棧空間,而我的系統上調用ulimit -a看到的結果如下:
[dengwei@localhost ~]$ 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) 15916
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
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) 1024
virtual memory (kbytes, -v) unlimited
core file size (blocks, -c) 0
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 15916
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
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) 1024
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
可以看到stack size是8M, 400個線程就需要8*400=3200M,虛擬內存不夠用。
解決辦法有兩種:
1.使用ulimit -s 1024*1024命令,將線程棧大小臨時設置成1M,經過試驗能同時創建2000個線程了。
2.使用pthread_attr_setstacksize在程序中改變線程棧大小。
"