C++11 equivalent of Windows SRWLock

自古美人都是妖i 提交于 2020-06-13 05:47:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/28151995/c11-equivalent-of-windows-srwlock

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