为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
Why in std::condition_variable notify_all works faster than notify_one (on random requests)?
我编写了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
之前释放互斥。
相关文章:
- condition_variable.notify是同步点吗
- QT C++如何调用lambda one
- 为什么'allocate in one library and free in the other'是错误的
- C++ WinRT - XAudio2是否支持Xbox One平台
- 为什么我收到错误:"there is more than one default constructor"?
- g++ 在我尝试用 ONE LINE 编译程序时崩溃了
- 在 ONE 设置中添加附加包含目录并引用 => 指向静态库
- 对于属性上的 NOTIFY 信号,如果我给它一个参数有什么区别?
- 为什么海湾合作委员会声称我违反了"at least one argument for variadic macro",而我至少有一个论点?
- "State pattern" vs "one member function per state" ?
- 编译时"one or more multiply defined symbols found"错误
- QApplication::notify()在捕获异常时应该返回什么
- 如何在QxORM中定义具有多个主键的表,其中一个主键是与另一个表的"many to one"关系
- VS 编译器错误 C2752 ( "more than one partial specialization matches" ) 在 STL 中
- one.cpp和two.cpp都包含两个.h
- 调用了基运算符而不是派生的one-Normal行为
- 如何使用多个 SVM 分类器(每个分类器都有一个特定的内核)作为"one vs rest classification"方案?
- 在C++程序中未使用libpq检索NOTIFY
- 什么是"one-stop memory corruption"?
- 重载运算符==抱怨'must take exactly one argument'