【发布时间】:2021-04-03 18:32:18
【问题描述】:
我对这个例子感到困惑:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *thread_func()
{
sleep(1); // removing this changes the result
printf("\n");
return NULL;
}
int main()
{
int i;
for (i = 0; i < 10000; i++)
{
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
}
pthread_exit(NULL);
return 0;
}
如果我使用sleep(1) 运行它,我会按预期计算 2047 行,没有它 10000。这是怎么回事?
编辑:将预期行数更正为 10000。
【问题讨论】:
-
你为什么期望 10000 个线程,每个打印一个空行,产生 3000 行?
-
你认为
pthread_exit(NULL);会做什么? -
10000 个线程非常多,您确定
pthread_create()有时不会因为达到某些限制而失败吗?你应该检查它的返回值来看看。
标签: c multithreading pthreads posix sleep