gpt4 book ai didi

c++ - 优化读写锁的实现

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:18:28 29 4
gpt4 key购买 nike

我目前正在使用 boost 库实现读/写锁,而不使用 shared_lock 和 unique_lock。我已经阅读了一些相关问题(例如 How would a readers/writer lock be implemented in C++11? ),但我仍然想优化实现。

这是我的代码:

enum LockType { NO_LOCK, READ_LOCK, WRITE_LOCK, INC_LOCK };
boost::mutex mutex_;
boost::condition condition_;
LockType lock_;
size_t owner_count_;

void AcquireReadLock() {
mutex_.lock();
while (lock_ != NO_LOCK && lock_ != READ_LOCK){
condition_.wait(mutex_);
}
// if there is no lock, then acquire read lock.
if (lock_ == NO_LOCK) {
lock_ = READ_LOCK;
++owner_count_;
mutex_.unlock();
return;
}
else {
// if there is read lock, then still acquire read lock.
assert(lock_ == READ_LOCK);
++owner_count_;
mutex_.unlock();
return;
}
}

void AcquireWriteLock() {
mutex_.lock();
while (lock_ != NO_LOCK){
condition_.wait(mutex_);
}
// if there is no lock, then acquire write lock.
assert(lock_ == NO_LOCK);
lock_ = WRITE_LOCK;
mutex_.unlock();
return;
}

void ReleaseReadLock() {
mutex_.lock();
--owner_count_;
if (owner_count_ == 0) {
lock_ = NO_LOCK;
}
mutex_.unlock();
// is it correct to use notify_all?
condition_.notify_all();
}

void ReleaseWriteLock() {
mutex_.lock();
lock_ = NO_LOCK;
mutex_.unlock();
// is it correct to use notify_all?
condition_.notify_all();
}

问题是:

  1. 释放锁时是否应该使用 notify_all?根据文档,线程一旦得到通知,就会重新获取锁。如果使用 notify_all,那么多个线程可以重新获取同一个锁。那么会发生什么?线程是否会在检查条件(即 lock_!=NO_LOCK && lock_!=READ_LOCK)之前获取锁?

  2. 如何优化程序?显然,当释放读锁时,我们只需要通知试图获取写锁的线程,因为读不会阻塞读。那么如何实现这个想法呢?

在此先感谢您的帮助!

最佳答案

  1. whether I should use notify_all when releasing the lock? According to the document, once a thread gets notified, it will reacquire the lock. If using notify_all, then multiple threads can reacquire the same lock. What will happen then? And whether will a thread acquire the lock before checking the condition (i.e., lock_!=NO_LOCK && lock_!=READ_LOCK)?

是的,释放锁时应该使用notify_all。所有等待 mutex_ 的 condition_ 都会被一个一个唤醒,因为它们必须首先锁定 mutex_(这是在 condition_wait 操作中完成的)。

  1. how can I optimize the program? obviously, when releasing a read lock, we only need to notify the threads that attempt to acquire the write lock, since read never blocks read. So how to implement this idea?

必须通知所有等待 mutex_ 的线程,因为一些写线程可能正在等待读锁被释放。

希望对您有所帮助!

关于c++ - 优化读写锁的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30044381/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com