所以我有一些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);
怎么办这样的事情?可能吗?
解决方法:
如果您让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锁.