How to implement a reader/writer lock in C++14

假装没事ソ 提交于 2019-12-01 10:16:29

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/31622059/how-to-implement-a-reader-writer-lock-in-c14

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!