如何在 C++14 中实现 reader/writer 锁
How to implement a reader/writer lock in C++14
我有一个散列 table 数据结构,我希望通过使用 reader/writer 锁使线程安全(我的 read:write 比率可能位于 100:1).
我一直在寻找如何使用 C++11 实现此锁(such as the method here), but it has come to my attention that it should be possible to use C++14's shared_lock
to accomplish the same thing. However, after looking on cppreference I have found both std::shared_lock
and std::unique_lock
but I don't understand how to use them together (compared to the Boost way which has simple method calls 用于唯一锁和共享模式锁)。
如何仅使用标准库在 C++14 中重新创建这个相对简单的 reader/writer 锁接口?
C++14 有 read/writer 锁实现 std::shared_timed_mutex
。
旁注:C++17 添加了更简单的 class std::shared_mutex
,如果您不需要额外的计时函数(如 shared_timed_mutex::try_lock_for
和 shared_timed_mutex::try_lock_until
).
但是,在使用 read/writer 锁之前,请注意 potentially harmful performance implications. Depending on the situation, a simple std::mutex
可能更快。
我有一个散列 table 数据结构,我希望通过使用 reader/writer 锁使线程安全(我的 read:write 比率可能位于 100:1).
我一直在寻找如何使用 C++11 实现此锁(such as the method here), but it has come to my attention that it should be possible to use C++14's shared_lock
to accomplish the same thing. However, after looking on cppreference I have found both std::shared_lock
and std::unique_lock
but I don't understand how to use them together (compared to the Boost way which has simple method calls 用于唯一锁和共享模式锁)。
如何仅使用标准库在 C++14 中重新创建这个相对简单的 reader/writer 锁接口?
C++14 有 read/writer 锁实现 std::shared_timed_mutex
。
旁注:C++17 添加了更简单的 class std::shared_mutex
,如果您不需要额外的计时函数(如 shared_timed_mutex::try_lock_for
和 shared_timed_mutex::try_lock_until
).
但是,在使用 read/writer 锁之前,请注意 potentially harmful performance implications. Depending on the situation, a simple std::mutex
可能更快。