[英]std::shared_mutex with std::shared_lock is reader or writer preferring?
In implementation of reader-writer lock, we can make use of the std::shared_mutex
with std::shared_lock
and std::lock_guard
or std::unique_lock
. 在实现读写器锁定时,我们可以将
std::shared_mutex
与std::shared_lock
和std::lock_guard
或std::unique_lock
。
Question > Is this new feature writer or reader preferring? 问题 >这个新功能作家还是读者更喜欢?
Update based on Andrew's comment 根据安德鲁的评论进行更新
// Multiple threads/readers can read the counter's value at the same time.
unsigned int get() const {
std::shared_lock<std::shared_mutex> lock(mutex_);
return value_;
}
// Only one thread/writer can increment/write the counter's value.
void increment() {
std::unique_lock<std::shared_mutex> lock(mutex_);
value_++;
}
As you can see from above example, I have no control on the reader/writer priority. 从上面的示例中可以看到,我无法控制读写器的优先级。
In practice: 在实践中:
pthread_rwlock_t
where available, falling back to the algorithm Howard mentioned if it is not. pthread_rwlock_t
,如果没有的话,可以回溯到霍华德提到的算法。 Therefore if pthread_rwlock_t
is available, the algorithm used depends on the pthreads implementation. pthread_rwlock_t
可用,则使用的算法取决于pthreads实现。 I believe that glibc prefers readers by default. MSVC uses Windows SRWLOCK
, whose documentation says MSVC使用Windows
SRWLOCK
,其文档说
There is no guarantee about the order in which threads that request ownership will be granted ownership;
无法保证请求所有权的线程被授予所有权的顺序。 SRW locks are neither fair nor FIFO.
SRW锁既不是公平的也不是FIFO。
It is neither (if implemented properly). 两者都不是(如果实施正确)。 Instead readers and writers are chosen to be next by a fair technique.
取而代之的是,读者和作家被公平的技术选为下一个。 And that is the reason that this characteristic is neither settable in the API, nor specified.
这就是无法在API中设置或指定该特性的原因。
This answer details how that is accomplished. 该答案详细说明了如何实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.