All notes
Multithread
http://stackoverflow.com/questions/38005626/why-does-add-function-have-no-effect-in-c-11-thread Bad example: #include #include #include #include #include void add(int& i){ std::mutex some_mutex; // std::cout << " I am " << std::endl; std::lock_guard guard(some_mutex); i++; } int main(){ int i = 0; std::vector 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; } // output: i = 0 // expected output: i = 10 Mutex needs to be shared between threads to get the correct result. And ibeing shadowed by loop variable, replace it with j. #include #include #include #include #include void add(int& i, std::mutex &some_mutex){ // std::cout << " I am " << std::endl; std::lock_guard guard(some_mutex); i++; } int main(){ int i = 0; std::vector 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; }
Mathematical formulae powered by MathJax.