gpt4 book ai didi

c++ - Boost 中的多读单写锁

转载 作者:IT老高 更新时间:2023-10-28 23:12:04 24 4
gpt4 key购买 nike

我正在尝试在多线程场景中实现以下代码:

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问题。但是,我不确定它是否适合上述 任何 读者可能成为作家的场景。文档指出:

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.

从“单一”这个词我怀疑只有一个线程可以持有可升级锁。其他人只持有共享锁,无法升级为独占锁。

您知道 boost::shared_lock 在这种情况下是否有用(任何读者都可能成为作家),或者是否有其他方法可以实现这一点?

最佳答案

是的,您可以按照接受的答案 here 中所示的方式做您想做的事。 .升级到独占访问的调用将被阻塞,直到所有读取器完成。

boost::shared_mutex _access;
void reader()
{
// get shared access
boost::shared_lock<boost::shared_mutex> lock(_access);

// now we have shared access
}

void writer()
{
// get upgradable access
boost::upgrade_lock<boost::shared_mutex> lock(_access);

// get exclusive access
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
// now we have exclusive access
}

关于c++ - Boost 中的多读单写锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4203467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com