【发布时间】:2020-06-05 19:25:38
【问题描述】:
我编写了 std::shared_mutex 的实现,但在我的测试中它工作了几分钟,将 notify_one 替换为 notify_all,它开始工作 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();
}
};
【问题讨论】:
-
请添加您的代码,以便我们更好地理解问题。
-
另外标准库里还有
shared_mutex,不需要自己实现rwlock。 -
@RinatVeliakhmedov 问题以“我编写了 std::shared_mutex 的实现”开头。
-
请提供minimal reproducible example。您是否在启用优化的情况下构建代码?
标签: c++ multithreading performance c++11 condition-variable