【发布时间】:2017-02-11 15:44:58
【问题描述】:
多次运行以下代码会产生相同数字多次出现的输出。我不确定为什么会这样。
#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。
-
我不明白等待他们的终止会如何改变他们的输出
-
确实加入解决了多值问题,但我不清楚为什么
标签: c++ multithreading pthreads