【发布时间】:2012-03-12 00:47:10
【问题描述】:
我对锁和互斥锁之间的区别感到非常困惑。在 Boost 文档中,它说,
锁类型
- 类模板 lock_guard
- 类模板 unique_lock
- 类模板 shared_lock
- 类模板 upgrade_lock
- 类模板 upgrade_to_unique_lock
- 互斥体特定类 scoped_try_lock
互斥类型
- 类互斥体
- 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
}
更新问题
- 谁能解释一下“互斥锁”和“锁”之间的关系?
- 是否需要为 shared_mutex 创建 shared_lock? 如果我为 shared_mutex 创建 unique_lock 会怎样?
- 或者如果我为 mutex 创建了 shared_lock,这是否意味着互斥锁可以 不能在多个线程之间共享?
【问题讨论】:
-
您可能会发现我的文章“互斥锁如何工作?”也很有帮助:mortoray.wordpress.com/2011/12/16/…
-
这些是新问题。你应该在一个新问题中问他们。您不会对已经存在的问题添加后续行动。此外,这些东西都在 Boost 的文档中。
标签: c++ multithreading boost mutex boost-thread