Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to learn the c++ 11 thread and have following code :

#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;
}

I have created a vector that holds std::thread and I call the add function from each thread and pass i by ref. After what I assumed that the thread would do (the adding of i = i+1), the end result does not reflect what I wanted.


output: i = 0

expected output: i = 10

like image 344
pokche Avatar asked Jun 24 '16 04:06

pokche


1 Answers

Mutex needs to be shared between threads to get the correct result. And ibeing shadowed by loop variable, replace it with 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;
}
like image 178
user1887915 Avatar answered Nov 11 '22 14:11

user1887915