Леонтий Хачуев Леонтий Хачуев - 4 months ago 43
C++ Question

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)


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

Something like this:

class Resource {
    T Read() { 
       std::lock_guard<std::mutex> lock(m_mutex);
       // read
    T Write() {
       std::lock_guard<std::mutex> lock(m_mutex);
       // write
    std::mutex m_mutex;