gpt4 book ai didi

c++ - 在 boost 中使用 scoped try_shared_lock 和升级锁的例子

转载 作者:搜寻专家 更新时间:2023-10-30 23:49:38 25 4
gpt4 key购买 nike

我有一个使用来自 boost 库的共享互斥体的线程池。

虽然我的其他问题的答案很有帮助, Example of how to use boost upgradeable mutexes

我意识到我真正需要的是在无法获得共享锁或升级锁时不阻塞。不幸的是,boost 文档缺少任何使用中的示例。

有人可以指点我或提供一个以这种方式使用 shared_lock 的具体示例。

boost:shared_mutex mutex;

void thread()
{
// try to obtain a scoped shared lock
// How do I do that?
}

void thread2()
{
// try to obtain a scoped upgrade lock
// and then a scoped unique lock
}

最佳答案

答案似乎是您可以将 boost:try_to_lock 作为参数提供给这些作用域锁中的几个。

例如

boost::shared_mutex mutex;

// The reader version
boost::shared_lock<boost::shared_mutex> lock(mutex, boost::try_to_lock);
if (lock){
// We have obtained a shared lock
}

// Writer version
boost::upgrade_lock<boost::shared_mutex> write_lock(mutex, boost::try_to_lock);
if (write_lock){
boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
// exclusive access now obtained.
}

编辑:我还通过实验发现,如果您没有升级锁,upgrade_to_unique_lock 将失败。您也可以这样做:

boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(write_lock);
if (unique_lock){
// we are the only thread in here... safe to do stuff to our shared resource
}

// If you need to downgrade then you can also call
unique_lock.release();

// And if you want to release the upgrade lock as well (since only one thread can have upgraded status at a time)
write_lock.unlock().

注意:您必须先调用 release 然后再调用 unlock,否则您将抛出锁定异常。你当然可以让 unique_lock 和 write_lock 超出范围从而释放锁,尽管我发现有时你想更早地释放它并且你应该花最少的时间在那个状态。

关于c++ - 在 boost 中使用 scoped try_shared_lock 和升级锁的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3963771/

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