为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请

Why in std::condition_variable notify_all works faster than notify_one (on random requests)?

本文关键字:notify one 于随机 condition std variable all 工作 为什么 速度      更新时间:2023-10-16

我编写了std::shared_mutex的实现,但在我的测试中,它工作了几分钟,用notify_all替换了notify_one,它开始工作20毫秒。这是因为只唤醒一个条件变量的开销,也是为什么它的工作速度比notify_all慢的原因。

class RWLock {
public:
template <class Func>
void Read(Func func) {
std::unique_lock<std::mutex> lock(mutex_);
no_writer_.wait(lock, [this] { return !write_; });
++read_cnt_;
lock.unlock();
try {
func();
} catch (...) {
End();
throw;
}
End();
}
template <class Func>
void Write(Func func) {
std::unique_lock<std::mutex> lock(mutex_);
no_readers_.wait(lock, [this] { return read_cnt_ == 0; });
write_ = true;
try {
func();
} catch (...) {
write_ = false;
throw;
}
write_ = false;
no_writer_.notify_all();
}
private:
std::mutex mutex_;
std::condition_variable no_writer_;
std::condition_variable no_readers_;
int read_cnt_ = 0;
bool write_ = false;
void End() {
mutex_.lock();
--read_cnt_;
no_readers_.notify_all();
mutex_.unlock();
}
};

在互斥锁锁定时发出条件信号。

您可以尝试一种常见的优化:在调用notify_one/notify_all之前释放互斥。