multithreading - Changing shared variables from multiple threads c++ -
i wondering if there way achieve changing shared/global variables multiple threads in c++
imagine code:
#include <vector> #include <thread> void pushanother(int x); std::vector<int> myarr; void main() { myarr.push_back(0); std::thread t1(pushanother, 2); t1.join(); } void pushanother(int x) { myarr.push_back(x); }
in particular case, code (barring lack of join on thread), surprisingly ok.
this because constructor of std::thread
causes memory fence operation , first thread not modify or read state of vector after fence.
in effect have transferred control of vector second thread.
however, modifying code represent more normal situation requires explicit locks:
#include <vector> #include <thread> #include <mutex> void pushanother(int x); // mutex handle contention of shared resource std::mutex m; // shared resource std::vector<int> myarr; auto push_it(int i) -> void { // take lock... auto lock = std::unique_lock<std::mutex>(m); // modify/read resource myarr.push_back(i); // ~lock implicitly releases lock } int main() { std::thread t1(pushanother, 2); push_it(0); t1.join(); } void pushanother(int x) { push_it(x); }
Comments
Post a Comment