當你下面的代碼:基本的多線程在C++(的執行順序)
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
cout << "Hello World! Thread ID, " << tid << endl;
pthread_exit(NULL);
}
int main()
{
pthread_t threads[NUM_THREADS];
int rc;
int i;
for(i=0; i < NUM_THREADS; i++){
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL,
PrintHello, (void *)i);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
the out put will be
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4
我很奇怪,爲什麼它不是
main() : creating thread, 0
Hello World! Thread ID, 0
main() : creating thread, 1
Hello World! Thread ID, 1
....
爲什麼我們創建線程,它會立即執行?
另一個問題線程0,1,2,3,4是否可能這些線程以隨機順序執行?例如,輸出將是
Hello World! Thread ID, 1
Hello World! Thread ID, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 2
Hello World! Thread ID, 3
非常感謝您的回答!
我的意思是當我們創建線程pthread_create(&threads [i],NULL, PrintHello,(void *)i);爲什麼不立即執行,那麼在我們創建第二個線程之前它會給出輸出 –
線程是異步執行的,所以它取決於操作系統的調度程序來決定運行它們的順序。您不能指望它們在任何特定訂購。 –
除非你使用同步。但是,沒有它,不要考慮任何執行順序。 – Desaroll