简体   繁体   中英

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. 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.
  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?
  4. There's a better way (faster) to try to acquire a lock for 'x' time than the two methods above specified?

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. 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.
  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.
  3. as far as I know you can't construct scoped_lock (which is basically unique_lock<timed_mutex> ) from posix_time. I personally prefer duration.
  4. In my opinion constructing the lock with Duration absolute time is your best option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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