每个线程都有自己的栈空间,用ulimit 可以查看系统的默认栈大小。
Linux创建线程数有最大的限制:
cat /proc/sys/kernel/threads-max 可以查看最大线程数。这个线程数是所有进程的线程数和。
[wenjie@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) 7932
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) 10240
cpu time (seconds, -t) unlimited
max user processes (-u) 1024
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
创建线程时,可以指定这个线程的栈大小
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
也可以用ulimit 命令更改
如: ulimit -s 16384
Linux有最小的栈要求,PTHREAD_STACK_MIN 默认为 16K
下面的代码,可以让你查看当前能创建的线程数,以及最后一个线程创建失败的原因。
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
void * entry(void *arg)
{
int num = *(int*)(arg);
while(1) {
sleep(1);
}
}
int main(int argc, char *argv[])
{
for (int i = 0; i < atoi(argv[1]); ++i) {
pthread_attr_t *attr = (pthread_attr_t*)malloc(sizeof(pthread_attr_t));
pthread_attr_init(attr);
int ret = pthread_attr_setstacksize(attr, 16384); // 24KB
if (ret != 0) {
perror("pthread_attr_setstacksize error.");
break;
}
pthread_t pth;
ret = pthread_create(&pth, attr, entry, &i);
if (ret != 0) {
printf("pthread_create error. has created conut = %d, error=%s\n", i, strerror(errno));
break;
}
}
while(1) {
sleep(10);
}
return 0;
}