为什么std :: condition_variable notify_all的运行速度比notify_one更快(在随机请求上?)>

问题描述 投票:1回答:1

我编写了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(); } };
我编写了std :: shared_mutex的实现,但是在我的测试中它工作了几分钟,用notify_all替换了notify_one,它开始工作了20毫秒。这是因为...
c++ multithreading performance c++11 condition-variable
1个回答
0
投票
您在互斥锁锁定时发出信号。

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

© www.soinside.com 2019 - 2024. All rights reserved.