4

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?

Community
  • 1
  • 1
Ephemera
  • 8,672
  • 8
  • 44
  • 84

1 Answers1

4

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.

Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239