答案似乎是您可以提供增强:尝试将锁定作为这些作用域锁中的几个的参数。
例如
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.
}
编辑:
我还通过实验发现,如果没有升级锁,升级到唯一锁将失败。您也可以这样做:
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超出范围,从而释放锁,尽管我发现有时您希望更早地释放它,您应该在这种状态下花费最少的时间。