[英]Does sleep() affect pthread execution?
我對這個例子感到困惑:
#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。
由於您的程序在退出之前不會等待其線程,因此發生的情況是它在退出程序之前有一個模糊定義的運行時間會破壞所有線程。
更新: pthread_exit
確實等待線程。 對於正在運行的線程。 我懷疑正在發生的事情是pthread_exit
創建的線程在pthread_create
之前沒有完全構建,然后程序退出。 部分線程構造發生在新線程中,因此如果它從未被安排運行,那么該線程可能也不存在。
創建 10,000 個線程需要時間。 摧毀他們也是如此。 與此同時,顯然有 3,000 個線程設法到達 printf 語句。
時間長短和打印數量取決於許多不同的因素,因此它也可能是隨機的。
拋開顯示的代碼試圖創建 10000 個線程,如果創建成功,將打印 10000 行而不是 3000 行,核心問題是:
如果每個線程等待 1s 與不等待相比,為什么print
ing 的線程更少?
可能的推理:
每個線程都吃掉資源。 因此,並發存在的最大線程數是有限的。
如果每個線程在結束前等待 1 秒,則可以假設可用資源比線程立即退出時消耗得更快。 因此,如果資源耗盡,線程的創建就會失敗,代碼會忽略它,而只是嘗試創建下一個線程。
要查看真正發生的事情,代碼應該記錄創建失敗的情況,如下所示:
#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 行,其中一些行是空的到stdout
,一些列出創建失敗到stderr
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.