Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock a resource (threads, C++)

I have two threads (first for read and second for write) and one shared resource (for example array). How to guard resource between threads? (block read, while second thread doing write) (Sorry for bad English)

like image 394
Леонтий Хачуев Avatar asked Dec 04 '25 11:12

Леонтий Хачуев


1 Answers

std::mutex wrapped in std::lock_guard is the easiest way for novice in multithreading.

Something like this:

class Resource {
public:
    T Read() { 
       std::lock_guard<std::mutex> lock(m_mutex);
       // read
    }  
    T Write() {
       std::lock_guard<std::mutex> lock(m_mutex);
       // write
    }
private:
    std::mutex m_mutex;
};
like image 129
Starl1ght Avatar answered Dec 07 '25 01:12

Starl1ght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!