简体   繁体   English

Mutex.timed_lock(duration)和boost :: timed_mutex :: scoped_lock scoped_lock(mutex,duration)之间的区别

[英]Difference between mutex.timed_lock(duration) and boost::timed_mutex::scoped_lock scoped_lock(mutex, duration)

I would like to know which is the difference between: 我想知道两者之间的区别:

boost::timed_mutex _mutex;
if(_mutex.timed_lock(boost::get_system_time() + boost::posix_time::milliseconds(10))){
   exclusive code
   _mutex.unlock();
}

and

boost::timed_mutex _mutex;
boost::timed_mutex::scoped_lock scoped_lock(_mutex, boost::get_system_time() + boost::posix_time::milliseconds(10));
if(scoped_lock.owns_lock()) {
   exclusive code
}

I do know already that the scoped_lock makes unnecessary the call to unlock. 我确实已经知道scoped_lock使得不必要进行解锁调用。 My question refers to: 我的问题是指:

  1. Why in the first case we call timed_lock as member function of a mutex and in the second one we construct a lock from a mutex and a duration. 为什么在第一种情况下我们将timed_lock称为互斥锁的成员函数,而在第二种情况下,我们根据互斥锁和持续时间构造了一个锁。
  2. Which one is more efficient? 哪一个更有效?
  3. The usage of boost::posix_time is okay or is recommended to use another kind, eg chrono or duration? 可以使用boost :: posix_time还是建议使用其他类型,例如计时或持续时间?
  4. There's a better way (faster) to try to acquire a lock for 'x' time than the two methods above specified? 与上面指定的两种方法相比,有一种更好的方法(更快)来尝试获得“ x”时间的锁定?

I'll try to answer your questions: 我会尽力回答您的问题:

  1. as you can read in this Document , locks are used as RAII devices for the locked state of a mutex. 如您在本文档中可以读到的,锁被用作互斥对象的锁定状态的RAII设备。 That is, the locks don't own the mutexes they reference. 也就是说,锁不拥有它们引用的互斥锁。 They just own the lock on the mutex. 他们只是拥有互斥锁。 basically what it means is that you acquire the mutex lock when you initialize it's corresponding lock and release it when the lock object is destroyed. 基本上,这意味着您在初始化互斥锁时会获取它的对应锁,并在销毁锁对象时释放互斥锁。
    that's why in the second example you didn't have to call timed_lock from the mutex, the scoped_lock does it for you when initialized. 这就是为什么在第二个示例中您不必从互斥锁调用timed_lock的原因,在初始化时scoped_lock会为您执行此操作。
  2. I don't know if the first example is more efficient but I know for sure that the second example (the RAII scoped_lock) is much safer, it guarantees that you won't forget to unlock the mutex and ,more important, it guarantees that other people that use and modify your code won't cause any mutex related problems. 我不知道第一个示例是否更有效,但是我确定第二个示例(RAII scoped_lock)更安全,它可以确保您不会忘记解锁互斥锁,更重要的是,它可以确保其他使用和修改您的代码的人不会引起任何与互斥锁有关的问题。
  3. as far as I know you can't construct scoped_lock (which is basically unique_lock<timed_mutex> ) from posix_time. 据我所知,您不能从posix_time构造scoped_lock(基本上是unique_lock<timed_mutex> )。 I personally prefer duration. 我个人更喜欢持续时间。
  4. In my opinion constructing the lock with Duration absolute time is your best option. 我认为,使用“持续时间”绝对时间构造锁是您的最佳选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM