Scoped Locking

Explicit Unlocking Considered Dangerous

What if a critical section throws?

lock.lock();
do_something_errorprone(); // possibly throws
do_more_of_it(); // possibly throws
lock.unlock();
  • Lock remains locked

  • ⟶ Deadlock

RAII - Resource Acquisition Is Initialization

Deterministic destructors

  • Objects are destroyed at end of block

  • Unlike Java, Python, … (garbage collection)

  • Exception safety!

Simplest: std::lock_guard

  • Obtains (single) lock in constructor

  • Releases lock in destructor

  • ⟶ good for single lock

std::lock_guard
...
// critical section
{
  std::lock_guard<std::mutex> g(lock); // lock.lock()
  do_something_errorprone();
  do_more_of_it();
  // ~guard does lock.unlock();
}
...