【问题标题】:Why in std::condition_variable notify_all works faster than notify_one (on random requests)?为什么在 std::condition_variable 中 notify_all 比 notify_one 工作得更快(在随机请求上)?
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 听起来更像是评论而不是答案。 优化解决问题吗?然后回答,但措辞不吉利。否则(真的只是尝试)应该是评论。
猜你喜欢
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-25
  • 2014-03-03
  • 1970-01-01
相关资源
最近更新 更多