为什么添加功能在c11线程中没有效果?

我正在尝试学习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的向量,我从每个线程调用add函数,并通过ref传递i.在我假设线程将会做的(添加i = i 1)之后,最终结果并不反映我想要的.

output: i = 0

expected output: i = 10

需要在线程之间共享Mutex以获得正确的结果.并且由循环变量阴影的ibeing替换为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;
}
http://stackoverflow.com/questions/38005626/why-does-add-function-have-no-effect-in-c-11-thread

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:为什么添加功能在c11线程中没有效果?