繁体   English   中英

为什么在 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之前释放互斥锁。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM