问题描述
我正在尝试在多线程场景中实现以下代码:
I'm trying to implement the following code in a multithreading scenario:
Get shared access to mutex
Read data structure
If necessary:
Get exclusive access to mutex
Update data structure
Release exclusive lock
Release shared lock
Boost 线程有一个 shared_mutex
类,它是为多读取器、单写入器模型设计的.有几个关于这个类的 stackoverflow 问题.但是,我不确定它是否适合上述任何 读者都可能成为作家的场景.文档指出:
Boost threads has a shared_mutex
class which was designed for a multiple-readers, single-writer model. There are several stackoverflow questions regarding this class. However, I'm not sure it fits the scenario above where any reader may become a writer. The documentation states:
UpgradeLockable 概念是一个SharedLockable 的细化允许升级的概念所有权和共享所有权和独家所有权.这是一扩展到多阅读器/提供的单写模型SharedLockable 概念:单一线程可能具有可升级的所有权在其他人分享的同时所有权.
The UpgradeLockable concept is a refinement of the SharedLockable concept that allows for upgradable ownership as well as shared ownership and exclusive ownership. This is an extension to the multiple-reader / single-write model provided by the SharedLockable concept: a single thread may have upgradable ownership at the same time as others have shared ownership.
从single"这个词我怀疑只有一个线程可以持有一个可升级的锁.其他人只持有共享锁,不能升级为排他锁.
From the word "single" I suspect that only one thread may hold an upgradable lock. The others only hold a shared lock which can't be upgraded to an exclusive lock.
你知道 boost::shared_lock
在这种情况下是否有用(任何读者都可能成为作者),或者是否还有其他方法可以实现这一点?
Do you know if boost::shared_lock
is useful in this situation (any reader may become a writer), or if there's any other way to achieve this?
推荐答案
boost::shared_lock
在这种情况下没有帮助(多个读者可以成为作者),因为只有一个线程可以拥有可升级的锁.问题文档中的引用以及查看代码 (threadwin32shared_mutex.hpp) 都暗示了这一点.如果一个线程试图获取一个可升级锁而另一个线程持有一个,它将等待另一个线程.
boost::shared_lock
doesn't help in this situation (multiple readers that can become writers), since only a single thread may own an upgradable lock. This is both implied by the quote from the documentation in the question, and by looking at the code (threadwin32shared_mutex.hpp). If a thread tries to acquire an upgradable lock while another thread holds one, it will wait for the other thread.
我决定为所有读取器/写入器使用常规锁,这对我来说没问题,因为临界区很短.
I settled on using a regular lock for all reader/writers, which is OK in my case since the critical section is short.
这篇关于Boost 中的多读者、单作者锁定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!