我正在研究線程和併發編程。嘗試從類中提供的基本示例:無法理解此基本線程行爲
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 8
void *printGoGators(void *noArg)
{
printf("Go Gators!\n");
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc, t;
for (t = 0; t < NUM_THREADS; t++)
{
printf("Creating thread %d\n", t);
rc = pthread_create(&threads[t],
NULL,
printGoGators,
NULL);
if(rc)
{
printf("ERROR %d", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
此代碼會生成以下輸出。 :
Creating thread 0
Creating thread 1
Go Gators!
Creating thread 2
Go Gators!
Creating thread 3
Go Gators!
Creating thread 4
Go Gators!
Creating thread 5
Go Gators!
Creating thread 6
Go Gators!
Creating thread 7
Go Gators!
Go Gators!
爲什麼Go Gators!
沒有直接與其對應的Creating thread #
所有線程後打印? 請幫忙!
因爲你的線程是相互獨立的並且來自創建它們的主線程。因此,一旦啓動,您無法控制首先打印哪個線程。 – HazemGomaa
所以這個問題被認爲是過於寬泛的計算器。我沒有看到有人提供不同的答案。 –
真的很難理解你的問題。你問爲什麼不發生任何理由,你爲什麼不應該發生。你正在看到你應該期待的行爲。如果你有其他期望,請說出爲什麼我們可以在你的推理中解釋錯誤。 –