I am trying to implement sample code for Reader writer problem but the below code is crashing in Reader API. In the code below, count
is my shared resource between reader and writer.
Here is the exception that throws in gcc compiler :
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
What's wrong in the code?
#include<iostream>
#include <thread>
#include <mutex>
using namespace std;
class ReaderAndWriter
{
mutex rmu;
mutex wmu;
int count = 20;
int readCount{ 0 };
public:
void Reader()
{
unique_lock<mutex> readLocker(rmu, std::defer_lock);
unique_lock<mutex> writeLocker(wmu, std::defer_lock);
readLocker.lock();
readCount++;
if (readCount == 1)
{
writeLocker.lock();
}
readLocker.unlock();
cout << "Reader " << count << endl;
readLocker.lock();
readCount--;
if (readCount == 0)
{
writeLocker.unlock();
}
readLocker.unlock();
}
void Writer()
{
unique_lock<mutex> locker(wmu);
count++;
cout << "writer " << count << endl;
locker.unlock();
}
void run()
{
std::thread reader1(&ReaderAndWriter::Reader, this);
std::thread reader2(&ReaderAndWriter::Reader, this);
std::thread reader3(&ReaderAndWriter::Reader, this);
std::thread writer1(&ReaderAndWriter::Writer, this);
std::thread writer2(&ReaderAndWriter::Writer, this);
reader1.join();
reader2.join();
reader3.join();
writer1.join();
writer2.join();
cout << "Success" << endl;
}
};
int main()
{
ReaderAndWriter rw;
rw.run();
return true;
}