64,646
社区成员
发帖
与我相关
我的任务
分享
class rwlock {
private:
mutex m;
condition_variable wcv,rcv;
unsigned writer, reader;
int active;
public:
rwlock() :writer(0), reader(0), active(0) {}
void readLock() {
unique_lock<mutex>lk(m);
++reader;
while (active < 0 || writer>0)rcv.wait(lk);
--reader;
++active;
}
//多个读者可以同时读文件
//写者在写文件时不允许有读者在读文件
//读者读时写者也不能写
void writeLock() {
unique_lock<mutex>lk(m);
++writer;
while (active != 0)wcv.wait(lk);
--writer;
active = -1;
}
void unlock() {
unique_lock<mutex>lock(mutex);
if (active > 0) {
--active;
if (active == 0)wcv.notify_one();
}
else {
active = 0;
if (writer > 0)wcv.notify_one();
else if (reader > 0)rcv.notify_all();
}
}
};