我对锁(lock)和互斥体(mutex)之间的区别非常困惑。在Boost文档中,它说:
锁类型
- 类模板lock_guard
- 类模板unique_lock
- 类模板shared_lock
- 类模板upgrade_lock
- 类模板upgrade_to_unique_lock
- 特定于互斥体的类scoped_try_lock
- 类mutex
- typedef try_mutex
- 类timed_mutex
- 类recursive_mutex
- typedef recursive_try_mutex
- 类recursive_timed_mutex
- 类shared_mutex
boost::shared_mutex _access;
void reader()
{
boost::shared_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
}
void conditional_writer()
{
boost::upgrade_lock< boost::shared_mutex > lock(_access);
// do work here, without anyone having exclusive access
if (something) {
boost::upgrade_to_unique_lock< boost::shared_mutex > uniqueLock(lock);
// do work here, but now you have exclusive access
}
// do more work here, without anyone having exclusive access
}
问题更新
- 请问有人能够解释一下 "mutex" 和 "lock" 的区别吗?
- 在使用 shared_mutex 时,是否需要创建一个 shared_lock?如果我为 shared_mutex 创建了一个 unique_lock 会发生什么?
- 如果我为 mutex 创建了一个 shared_lock,是否意味着该互斥量不能在多个线程之间共享?