我正在尝试学习c ++ 11线程并拥有以下代码:
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <algorithm>
void add(int& i){
std::mutex some_mutex;
// std::cout << " I am " << std::endl;
std::lock_guard<std::mutex> guard(some_mutex);
i++;
}
int main(){
int i = 0;
std::vector<std::thread> vec_threads;
for(int i = 0; i < 10; i++){
vec_threads.push_back(std::thread(add,std::ref(i)));
}
std::for_each(vec_threads.begin(),vec_threads.end(),
std::mem_fn(&std::thread::join));
std::cout<< " i = " << i << std::endl;
return 0;
}
我创建了一个vector
,其中包含std::thread
,我从每个线程调用add函数并通过ref传递i。在假设线程会做的事情之后(添加i = i+1
),最终结果并不反映我想要的。
输出:i = 0
预期产出:i = 10
答案 0 :(得分:28)
需要在线程之间共享互斥锁以获得正确的结果。并且i
被循环变量遮蔽,请将其替换为j
。
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
#include <algorithm>
void add(int& i, std::mutex &some_mutex){
// std::cout << " I am " << std::endl;
std::lock_guard<std::mutex> guard(some_mutex);
i++;
}
int main(){
int i = 0;
std::vector<std::thread> vec_threads;
std::mutex some_mutex;
for(int j = 0; j < 10; j++){
vec_threads.push_back(std::thread(add,std::ref(i), std::ref(some_mutex)));
}
std::for_each(vec_threads.begin(),vec_threads.end(),
std::mem_fn(&std::thread::join));
std::cout<< " i = " << i << std::endl;
return 0;
}