Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

    #include <iostream>
    #include <mutex>
    #include <thread>

    class SharedResource {
    private:
        int value;
        std::mutex mtx;

    public:
        SharedResource() : value(0) {}

        void setValue(int newValue) {
            std::lock_guard<std::mutex> guard(mtx);
            value = newValue;
        }

        int getValue() {
             std::lock_guard<std::mutex> guard(mtx);
             return value;
       }
   };

   void threadFunction(SharedResource& resource) {
       resource.setValue(42);
      std::cout << "Value: " << resource.getValue() <<   std::endl;
    }

    int main() {
        SharedResource resource;
        std::thread t1(threadFunction, std::ref(resource));
        std::thread t2(threadFunction, std::ref(resource));

        t1.join();
        t2.join();

       return 0;
   }


This prevents access to the variable being protected by the mutex.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: