News for hackers. Stuff that matters.
Re:Inside Rust's std and parking_lot mutexes – who wins? by mrlonglong on Thursday November 27, 2025 @05:34PM (#46073778)

    #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;
   }
Re:Inside Rust's std and parking_lot mutexes – who wins? by mrlonglong on Thursday November 27, 2025 @05:38PM (#46073807)
This prevents access to the variable being protected by the mutex.