What's the difference between "mutex" and "lock"?

2607 picture 2607 · Feb 21, 2012 · Viewed 17.1k times · Source

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

Lock Types

  • Class template lock_guard
  • Class template unique_lock
  • Class template shared_lock
  • Class template upgrade_lock
  • Class template upgrade_to_unique_lock
  • Mutex-specific class scoped_try_lock

Mutex Types

  • Class mutex
  • Typedef try_mutex
  • Class timed_mutex
  • Class recursive_mutex
  • Typedef recursive_try_mutex
  • Class recursive_timed_mutex
  • Class 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
}

Updated questions

  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?

Answer

Anthony Williams picture Anthony Williams · Feb 21, 2012

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.