如何在C ++ 14中实现读写器锁 [英] How to implement a reader/writer lock in C++14
问题描述
我有一个哈希表数据结构,希望通过使用读取器/写入器锁来使线程安全(我的读/写比可能在100:1的范围内).
我一直在寻找如何使用C ++ 11实现此锁定的方法( cppreference 之后,我同时发现了std::shared_lock
和
如何仅使用标准库在C ++ 14中重新创建此相对简单的读取器/写入器锁定接口?
C ++ 14具有读/写锁实现 std::shared_mutex
,如果不需要额外的计时功能(例如shared_timed_mutex::try_lock_for
和shared_timed_mutex::try_lock_until
),可以使用它.
但是,在使用读/写锁之前,请注意潜在的有害性能影响.根据情况,一个简单的 std::mutex
可能会更快.>
I have a hash table data structure that I wish to make thread safe by use of a reader/writer lock (my read:write ratio is likely somewhere in the region of 100:1).
I have been looking around for how to implement this lock using 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 for locking both uniquely and in shared mode).
How can I recreate this relatively simple reader/writer lock interface in C++14 using only the standard library?
C++14 has the read/writer lock implementation std::shared_timed_mutex
.
Side-note: C++17 added the simpler class std::shared_mutex
, which you can use if you don't need the extra timing functions (like shared_timed_mutex::try_lock_for
and shared_timed_mutex::try_lock_until
).
However, before using a read/writer lock, be aware of the potentially harmful performance implications. Depending on the situation, a simple std::mutex
might be faster.
这篇关于如何在C ++ 14中实现读写器锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!