C++11 相当于 Windows SRWLock
C++11 equivalent of Windows SRWLock
我正在尝试使用原子类型实现我自己的 read/write 锁。我可以很容易地定义独占锁,但我无法像 SRWLock 那样为共享 reader 线程创建锁(请参阅 SRWLock)。我的问题是如何实现可以在独占模式(一次一个 reader/writer 线程)或共享模式(一次多个 reader 线程)中使用的锁。
我无法使用 std::mutex
锁,因为它不支持多个 reader。我也不使用 boost,所以也没有 shared_mutex
。
共享定时互斥体
C++11 标准库中没有与这种读写锁定等效的方法。好消息是 C++14 中有一个,叫做 shared_timed_mutex
.
看这里:
http://en.cppreference.com/w/cpp/thread/shared_timed_mutex
编译器支持
根据 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,GCC 的最新版本支持 shared_timed_mutex
,其中表示缺少 C++ 中的共享锁定。
可能的替代方案
如果您使用具有这些原语的库,则可以使用互斥锁和信号量 as described in this tutorial 来实现这种事情。
如果您更喜欢使用标准库,您可以使用类似于 how it's done here or here 的 std::mutex
和 std::condition_variable
来实现这些内容。
在boost中也有shared_mutex
(正如你已经提到的),或者在libuv中有uv_rwlock_t
, 或在类 unix 操作系统中 pthread_rwlock
。
我正在尝试使用原子类型实现我自己的 read/write 锁。我可以很容易地定义独占锁,但我无法像 SRWLock 那样为共享 reader 线程创建锁(请参阅 SRWLock)。我的问题是如何实现可以在独占模式(一次一个 reader/writer 线程)或共享模式(一次多个 reader 线程)中使用的锁。
我无法使用 std::mutex
锁,因为它不支持多个 reader。我也不使用 boost,所以也没有 shared_mutex
。
共享定时互斥体
C++11 标准库中没有与这种读写锁定等效的方法。好消息是 C++14 中有一个,叫做 shared_timed_mutex
.
看这里:
http://en.cppreference.com/w/cpp/thread/shared_timed_mutex
编译器支持
根据 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,GCC 的最新版本支持 shared_timed_mutex
,其中表示缺少 C++ 中的共享锁定。
可能的替代方案
如果您使用具有这些原语的库,则可以使用互斥锁和信号量 as described in this tutorial 来实现这种事情。
如果您更喜欢使用标准库,您可以使用类似于 how it's done here or here 的 std::mutex
和 std::condition_variable
来实现这些内容。
在boost中也有shared_mutex
(正如你已经提到的),或者在libuv中有uv_rwlock_t
, 或在类 unix 操作系统中 pthread_rwlock
。