Synchronization
Anonymous User
901

Question:
When a write is happening, no other thread should be allowed to read/write.
When a read is happening, no other thread should be allowed to write.

Please let me know if my solution below is correct:

class Solution
{
    mutex m, writeLock;
    condition_variable cv;
    int readCounter = 0;

    void read()
    {
        writeLock.lock();
        readCounter++; //number of threads reading
        writeLock.unlock();
        cout << "reading data from data, this will take some time";
        this_thread::sleep_for(100ms);
        readCounter--;
        cv.notify_one();
    }

    void write()
    {
        writeLock.lock();
        unique_lock<mutex> lock(m);
        cv.wait(lock, [this] {return readCounter == 0; });
        cout << "writing data to database";
        this_thread::sleep_for(1000ms);
        writeLock.unlock();
    }
};
Comments (2)