相当于Windows SRWLock的C ++ 11 [英] C++11 equivalent of Windows SRWLock
问题描述
我正在尝试使用原子类型实现自己的读/写锁.我可以轻松定义互斥锁,但无法像SRWLock一样为共享的读取器线程创建锁(请参阅解决方案
共享定时互斥锁
在C ++ 11标准库中,没有等同于这种读写锁定的方法.好消息是C ++ 14中有一个叫做shared_timed_mutex
.
在这里看看:
http://en.cppreference.com/w/cpp/thread/shared_timed_mutex
编译器支持
GCC的最新版本根据如果使用-std=c++14
编译器标志,则其文档.坏消息是Visual C ++还不支持它,或者至少我还没有找到有关它的任何具体信息,我得到的最接近的东西是在本教程中,如果您使用具有这些原语的库.
如果您喜欢使用标准库,则可以使用std::mutex
和std::condition_variable
来实现这些内容,类似于此处.
在 boost 中也有shared_mutex
(如您已经提到的),在 libuv 中也有uv_rwlock_t
,在类unix的OS中也有pthread_rwlock
./p>
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.
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.
这篇关于相当于Windows SRWLock的C ++ 11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!