我使用下面的命令查看我的系统允许的最大线程数:
# cat /proc/sys/kernel/threads-max
号码是772432。
但是,我使用下面的代码来创build100万个线程。 它工作。
#include <pthread.h> #include <stdio.h> static unsigned long long thread_nr = 0; pthread_mutex_t mutex_; void* inc_thread_nr(void* arg) { /* int arr[1024][1024]; */ (void*)arg; pthread_mutex_lock(&mutex_); thread_nr ++; pthread_mutex_unlock(&mutex_); } int main(int argc, char *argv[]) { int err; int cnt = 0; pthread_mutex_init(&mutex_, NULL); while (cnt < 1000000) { pthread_t pid; err = pthread_create(&pid, NULL, (void*)inc_thread_nr, NULL); if (err != 0) { break; } pthread_join(pid, NULL); cnt++; } pthread_mutex_destroy(&mutex_); printf("Maximum number of threads per process is = %d\n", thread_nr); }
输出是:
Maximum number of threads per process is = 1000000
这大于最大线程数。 这是什么原因? 而且是由pthread_create
创build的线程与内核线程一样吗?
我的操作系统是Fedora 16,有12个内核,48G内存。
你不应该用%d打印你的无符号long long。
使用
printf("... %llu\n", thread_nr);
代替。