C++ 11 feature: C++ Multithreading Tutorial: std::lock

std::lock is used to lock multiple mutex at the same time.

Syntax:

styntax: std::lock(m1, m2, m3, m4);

It will be able to lock all the objects in a non deadlock way by using deadlock avoidance algorithm.

It will make series of lock, try_lock, and unlock to achieve this.

It is a blocking call.

The order of locking is undefined.

If there is an exception while calling lock or unlock, then it will first unlock all the mutex objects and then throws an exception.

Example:

#include <iostream>       // std::cout
#include <future>         // std::async, std::future
#include <chrono>         // std::chrono::milliseconds
#include <thread>         // std::thread
#include <mutex>          // std::timed_mutex

// for more tutorials visit www.ProDeveloperTutorial.com
using namespace std;

std::mutex m1, m2;

void task_a () 
{
  // m1.lock(); m2.lock(); // replaced by:
  std::lock (m1, m2);
  std::cout << "task a\n";
  m1.unlock();
  m2.unlock();
}

void task_b () 
{
  // m2.lock(); m1.lock(); // replaced by:
  std::lock (m2,m1);
  std::cout << "task b\n";
  m2.unlock();
  m1.unlock();
}

int main ()
{
  std::thread th1 (task_a);
  std::thread th2 (task_b);

  th1.join();
  th2.join();

  return 0;
}

Output:

task a
task b

The above is not a deadlock situation.

Write a Comment

Leave a Comment

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