C sleep()是否影响pthread执行?
我对这个例子感到困惑:C sleep()是否影响pthread执行?,c,multithreading,pthreads,posix,sleep,C,Multithreading,Pthreads,Posix,Sleep,我对这个例子感到困惑: #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
#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;
}
如果我用sleep1运行这个程序,我会计算2047行,没有它,就像预期的10000行。这是怎么回事
编辑:将预期的行数更正为10000。由于您的程序在退出之前不等待线程,因此,在退出程序之前,它有一个模糊定义的运行时间来销毁所有线程 更新:pthread_exit不等待线程。对于正在运行的线程。我怀疑正在发生的是,pthread_create创建的线程在pthread_退出然后程序退出之前没有完全构造。线程构造的一部分发生在新线程中,因此如果它从未计划运行,那么该线程也可能不存在 创建10000个线程需要时间。摧毁它们也是如此。同时,3000个线程设法到达printf语句
打印的时间和数量取决于许多不同的因素,因此也可能是随机的。抛开显示的代码试图创建10000个线程,如果创建成功,将打印10000行而不是3000行,核心问题是: 为什么与不等待相比,如果每个线程等待1s,打印的线程会更少 可能的理由: 每个线程都会占用资源。因此,并发存在的最大线程数是有限的 如果每个线程在结束前等待1s,则可以假定可用资源的消耗速度比线程立即退出快。因此,如果资源耗尽,线程的创建就会失败,代码会忽略这一点,而只是尝试创建下一个线程 要查看实际情况,代码应记录创建失败的情况,如下所示:
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
void *thread_func(void)
{
sleep(1); /* Removing this probably lowers the number of failed creations. */
printf("\n");
return NULL;
}
int main(void)
{
int i;
for (i = 0; i < 10000; i++)
{
pthread_t tid;
if (errno = pthread_create(&tid, NULL, thread_func, NULL))
{
perror("pthread_create() failed");
}
}
pthread_exit(NULL);
/* Never arriving here. */
return 0;
}
上述代码打印的行数预计总共为10000行,其中一些行为空,进入标准输出,一些列示创建失败的行进入标准输出。为什么您希望10000个线程,每个线程打印一个空行,生成3000行?您认为pthread_exitNULL;是吗?10000个线程太多了,您确定pthread_create有时不会因为达到某个限制而失败吗?您应该检查其返回值以查看。通过调用pthread_exit离开main不会结束进程,而不仅仅是返回主线程。感谢您的回答,您的怀疑当然是正确的。pthread_创建失败。我选择了另一个答案是因为perror检查。是的,谢谢你,这确实解决了这个谜。我从不使用C语言编程,否则我可能会本能地检查错误。当我这样做时./threads_corrected 2>&1 | grep-I失败| wc-l。。。我看到了丢失的7953次失败的尝试!