upd: write class ReadWriteLock
This commit is contained in:
@ -65,7 +65,20 @@ BlockingStringStream &BlockingStringStream::operator>>(T &val) {
|
|||||||
|
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
class ReadWriteLock {
|
||||||
|
private:
|
||||||
|
std::mutex mtx;
|
||||||
|
std::condition_variable cv;
|
||||||
|
int readers;
|
||||||
|
bool is_writing;
|
||||||
|
|
||||||
|
public:
|
||||||
|
ReadWriteLock();
|
||||||
|
void startRead();
|
||||||
|
void endRead();
|
||||||
|
void startWrite();
|
||||||
|
void endWrite();
|
||||||
|
};
|
||||||
class SessionClass {
|
class SessionClass {
|
||||||
std::stack<int> login_stack;
|
std::stack<int> login_stack;
|
||||||
std::string SessionToken;
|
std::string SessionToken;
|
||||||
|
@ -11,3 +11,33 @@ BlockingStringStream &BlockingStringStream::getline(std::string &str,
|
|||||||
|
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ReadWriteLock::ReadWriteLock() : readers(0), is_writing(false) {}
|
||||||
|
|
||||||
|
void ReadWriteLock::startRead() {
|
||||||
|
std::unique_lock<std::mutex> lock(mtx);
|
||||||
|
cv.wait(lock, [this] { return !is_writing; }); // 等待写操作结束
|
||||||
|
readers++;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReadWriteLock::endRead() {
|
||||||
|
std::unique_lock<std::mutex> lock(mtx);
|
||||||
|
readers--;
|
||||||
|
if (readers == 0) {
|
||||||
|
cv.notify_one(); // 唤醒一个等待的写操作
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReadWriteLock::startWrite() {
|
||||||
|
std::unique_lock<std::mutex> lock(mtx);
|
||||||
|
cv.wait(lock, [this] {
|
||||||
|
return readers == 0 && !is_writing;
|
||||||
|
}); // 等待读操作和写操作结束
|
||||||
|
is_writing = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void ReadWriteLock::endWrite() {
|
||||||
|
std::unique_lock<std::mutex> lock(mtx);
|
||||||
|
is_writing = false;
|
||||||
|
cv.notify_all(); // 唤醒所有等待的读操作和写操作
|
||||||
|
}
|
Reference in New Issue
Block a user