"mutex"和"mutex"之间有什么区别和“锁定"? [英] What's the difference between "mutex" and "lock"?

查看:143
本文介绍了"mutex"和"mutex"之间有什么区别和“锁定"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对锁和互斥锁之间的区别感到非常困惑.在Boost文档中,它说

I am very confused about the difference between a lock and mutex. In Boost docs, it says,

锁定类型

  • 类模板lock_guard
  • 类模板unique_lock
  • 类模板shared_lock
  • 类模板upgrade_lock
  • 类模板upgrade_to_unique_lock
  • Mutex特定的类scoped_try_lock

互斥类型

  • 互斥锁
  • Typedef try_mutex
  • timed_mutex类
  • recursive_mutex类
  • Typedef recursive_try_mutex
  • recursive_timed_mutex类
  • shared_mutex类

在另一篇文章中,我看到了类似的功能

In another article, I see functions like this,

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
}

更新的问题

  1. 有人可以在互斥体"和锁定"之间提供一些澄清吗?
  2. 是否有必要为 shared_mutex 创建 shared_lock ? 如果为 shared_mutex 创建 unique_lock ,会发生什么情况?
  3. 或者,如果我为互斥锁创建了 shared_lock ,这是否意味着互斥锁可以 不能在多个线程之间共享?
  1. Can anyone offer some clarification between the "mutex" and "lock"?
  2. Is it necessary to create a shared_lock for a shared_mutex? What happen if I create a unique_lock for a shared_mutex?
  3. Or if I create a shared_lock for a mutex, does it mean the mutex can not be shared among multiple threads?

推荐答案

互斥体是一个同步对象.您可以在代码部分的开头获取互斥锁的锁定,然后在末尾释放该互斥锁,以确保没有其他线程同时访问同一数据.一个互斥锁的生存期通常等于它所保护的数据的生存期,并且一个互斥锁可以被多个线程访问.

A mutex is a synchronization object. You acquire a lock on a mutex at the beginning of a section of code, and release it at the end, in order to ensure that no other thread is accessing the same data at the same time. A mutex typically has a lifetime equal to that of the data it is protecting, and that one mutex is accessed by multiple threads.

锁对象是封装该锁的对象.构造对象时,它将获取互斥锁.当它被破坏时,锁被释放.通常,您每次访问共享数据都会创建一个新的锁定对象.

A lock object is an object that encapsulates that lock. When the object is constructed it acquires the lock on the mutex. When it is destructed the lock is released. You typically create a new lock object for every access to the shared data.

这篇关于"mutex"和"mutex"之间有什么区别和“锁定"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆