3

I'm trying to implement my own read/write lock using atomic types. I can easily define exclusive locks, but I fail to create locks for shared reader threads, like SRWLock does (see SRWLock). My question is how to implement locks that can be used in exclusive mode (one reader/writer threads at a time) or in shared mode (multiple reader threads at a time).

I can't use std::mutex lock because it doesn't support multiple readers. Also I don't use boost, so no shared_mutex either.

rashmatash
  • 1,699
  • 13
  • 23
  • Implement your own that wraps SRWLock and meets the requirements of [BasicLockable](http://en.cppreference.com/w/cpp/concept/BasicLockable)? – Mgetz Jan 26 '15 at 14:39
  • 1
    [N2406](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2406.html#shared_mutex_imp) has a reference implementation of `shared_mutex` that can easily be adapted. – T.C. Jan 26 '15 at 15:08
  • Duplicate of http://stackoverflow.com/q/27860685/576911 ? – Howard Hinnant Jan 26 '15 at 17:11

1 Answers1

2

The shared timed mutex

There is no equivalent for that kind of read-write locking in the C++11 standard library. The good news is that there is one in C++14 and it's called shared_timed_mutex.

Take a look here:
http://en.cppreference.com/w/cpp/thread/shared_timed_mutex

Compiler support

GCC's recent versions support shared_timed_mutex according to its documentation if you use the -std=c++14 compiler flag. The bad news is that Visual C++ doesn't support it yet, or at least I haven't been able to find any concrete info about it, the closest thing I got is this feature table which says that Shared Locking in C++ is missing.

Possible alternatives

You can implement this kind of thing using a mutex and a semaphore as described in this tutorial if you use a library that has these primitives.

If you prefer to stay with the standard library, you can implement the stuff with an std::mutex and an std::condition_variable similarly to how it's done here or here.

There is also shared_mutex in boost (as you already noted), or uv_rwlock_t in libuv, or pthread_rwlock in unix-like OSes.

Community
  • 1
  • 1
Venemo
  • 18,515
  • 13
  • 84
  • 125