Difference between std::lock_guard and std::unique_lock in C++

In this tutorial, we will learn the difference between std::lock_guard and std::unique_lock in C++.

Before proceeding to the differences, let us discuss the std::lock_guard and std::unique_lock briefly.

The characteristics of std::lock_guard are:

  • It holds the lock from the time of construction until the time of destruction.
  • When it is created, it tries to take control of the mutex which contains resources, it is provided. When this control is over, the std::lock_guard will destroy and mutex frees.
  • It is defined under the header file mutex.h.

Syntax:

template < class Mutex > //Mutex is the resource to lock
class Std_lock_guard;

The characteristics of std::unique_lock are:

  • It does not lock as soon as it is created and unlocks at any time within the time it exists.
  • It is similar to std::lock_guard but provides many methods for locking, unlocking and removing locks.
  • This transfers lock ownership from one instance of the resource to another.
  • It is defined under the header file mutex.h.

Syntax:

template < class Mutex > //Mutex is the resource to lock
class Std_unique_lock;

Difference between std::lock_guard and std::unique_lock

The programmer does not have the ability to unlock the std::lock_guard but he can unlock the std::unique_lock.

The object creation in std::lock_guard and std::unique_lock is as follows:

std::lock_guard lock1(resource); // resource is the resouce to lock and lock1 is the object
std::unique_lock lock2(resource); // resource is the resource to lock and lock2 is the object

The constructor of the object lock1 locks the resource and when the object scope is over, the object destructor unlocks the mutex.

The constructor of the object lock2 locks the resource and the object destructor unlocks the mutex. The difference is that the std::unique_lock consists of various other functionalities.

The programmer has the ability to unlock the resources with the lock object in the case of std::unique_lock.

lock2.unlock();

Recommended Posts:
Difference between NULL and nullptr in C++

Leave a Reply

Your email address will not be published. Required fields are marked *