多次运行以下代码会在同一个数字出现多次时产生输出。我不确定这是为什么。为什么此代码多次输出相同的数字?
#include <iostream>
#include <pthread.h>
using namespace std;
const int NUM_THREADS = 5;
void* thread_entry(void *i){
cout<<(long)i<<endl;
}
int main() {
pthread_t threads[NUM_THREADS];
long i;
for(i=0;i<NUM_THREADS;i++){
pthread_create(&threads[i],NULL,&thread_entry,(void *)i);
}
return 0;
}
它编译g++ -std=c++11 main.cpp -lpthread
。
输出:
$ ./a.out
0
1
4
$ ./a.out
014
14
23
$ ./a.out
02
2
3
您是否考虑加入您的主题? –
你需要加入你的线程,并且你需要一个互斥体或类似的来保护你的输出到cout,而且目前是交错的值。你可能也想考虑使用std :: thread。 –
我没有看到如何等待他们的终止会改变他们的输出 – Adam