为什么 add 函数在 C++ 11 线程中不起作用?

Why does add function have no effect in c++ 11 thread?

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


output: i = 0

expected output: i = 10

Mutex 需要在线程之间共享以获得正确的结果。并且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;
}