【发布时间】:2012-09-12 12:06:19
【问题描述】:
可能重复:
The thread create by pthread_create the same with the kernel thread?
我使用下面的代码来测试 pthread_create 函数可以创建的最大线程数。
#include <pthread.h>
#include <stdio.h>
static unsigned long long thread_nr = 0;
pthread_mutex_t mutex_;
void* inc_thread_nr(void* arg) {
(void*)arg;
pthread_mutex_lock(&mutex_);
thread_nr ++;
pthread_mutex_unlock(&mutex_);
/* printf("thread_nr = %d\n", thread_nr); */
sleep(300000);
}
int main(int argc, char *argv[])
{
int err;
int cnt = 0;
pthread_t pid[1000000];
pthread_mutex_init(&mutex_, NULL);
while (cnt < 1000000) {
err = pthread_create(&pid[cnt], NULL, (void*)inc_thread_nr, NULL);
if (err != 0) {
break;
}
cnt++;
}
pthread_join(pid[cnt], NULL);
pthread_mutex_destroy(&mutex_);
printf("Maximum number of threads per process is = %d\n", thread_nr);
}
输出是:
Maximum number of threads per process is = 825
这是 pthread_create 函数可以创建的最大线程数吗?
此外,我使用以下命令查看我的系统允许的最大线程数:
# cat /proc/sys/kernel/threads-max
号码是772432。
为什么我的程序的输出不等于threads-max的值?
我的操作系统是 Fodaro 16,有 12 个内核,48G RAM。
【问题讨论】:
-
pthread_create()函数只能创建一个线程。您可以多次调用它——显然 825 没有错误。这可能会随着系统加载、流程变化和其他变量的变化而变化。 -
@iccthedral 它们不是重复的。他们关注不同的方面和不同的问题。
-
请告诉我为什么需要这么多线程?
-
请告诉我们
errno您观察到了什么。 -
最后一行应该是
printf("Maximum number of threads per process is = %d\n", cnt);