Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 equivalent of Windows SRWLock

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.

like image 765
rashmatash Avatar asked Oct 24 '25 06:10

rashmatash


1 Answers

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.

like image 104
Venemo Avatar answered Oct 26 '25 18:10

Venemo