C++11 multiple read and one write thread mutex [duplicate]

Pretty close, couple things to note, in c++ for exception safety and readability, IMO, it is good to use RAII locks. What you really need is a shared_mutex like in boost or coming in c++14.

std::shared_mutex write; //use boost's or c++14 

// One write, no reads.
void write_fun()
{
    std::lock_guard<std::shared_mutex> lock(write);
    // DO WRITE
}

// Multiple reads, no write
void read_fun()
{
    std::shared_lock<std::shared_mutex> lock(write);
    // do read
}

If you don’t want to use boost @howardhinmant was do kind as to give a link to a reference implementation

Leave a Comment