gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:35:53 30 4
gpt4 key购买 nike

我编写了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之前释放互斥量。

关于c++ - 为什么在std::condition_variable notify_all的运行速度比notify_one更快(在随机请求上)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60337398/

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