【发布时间】:2016-10-26 14:45:00
【问题描述】:
我正在尝试学习 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;
}
我创建了一个包含std::thread 的vector,我从每个线程调用add 函数并通过引用传递i。在我假设线程会做的事情(添加i = i+1)之后,最终结果并没有反映我想要的。
输出:i = 0
预期输出:i = 10
【问题讨论】:
-
@Ajay 但 user1887915 也对我为每个线程创建的互斥锁持正确态度......这是个糟糕的主意。
标签: c++ multithreading c++11 output stdthread