This is safe, but still likely not fair or performant:
std::atomic readers;
std::mutex write;
// One write, no reads.
void write_fun()
{
write.lock();// We lock the resource
while(readers > 0){}// We wait till everyone finishes read.
// DO WRITE
write.unlock();// Release
}
// Multiple reads, no write
void read_fun()
{
// We wait if it is being written.
write.lock();
readers++;
write.unlock();
// do read
readers--;
}
A solution with condition variables could avoid busy waiting for readers
to fall to 0, left as an exercise for the reader.