所以我有一些shared_mutex并完成了这个:
boost::upgrade_lock<boost::shared_mutex> lock(f->mutex);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
现在我想“解锁”或者至少将其降级为:
boost::shared_lock<boost::shared_mutex> lock_r(f->mutex);
怎么做这样的事情?有可能吗?
答案 0 :(得分:9)
如果您让upgrade_to_unique_lock
超出范围,它将自动降级回升级所有权。
例如
void foo() {
boost::upgrade_lock<boost::shared_mutex> lock(f->mutex);
// Do shared operations, as mutex is held upgradeable
// ...
if(need_to_get_unique)
{
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
// Do exclusive operations, as mutex is held uniquely
// ...
// At end of scope unique is released back to upgradeable
}
// Only shared operations here, as it's only held upgradeable
// ...
// At end of scope mutex is completely released
}
编辑:另一件事。如果给定函数仅需要排他锁,则可以使用boost::unique_lock
并唯一锁定,而无需同时执行upgrade
和upgrade_to_unique
锁定。