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

1. try_lock is used to lock multiple mutex.

2. try_lock is used to lock the objects by using try_lock member functions.

3. It is a non blocking call

4. It tries to lock all the objects in the given order

5. On success it will return -1 otherwise it will return 0-based mutex index number which it could not lock

6. If it fails to lock any of the mutex then it will release all the mutex it locked before.

7. If a call to try_lock results in an exception, unlock is called for any locked objects before re-throwing.

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();
  std::cout << "task a\n";
  m2.lock();

  m1.unlock();
  m2.unlock();
}

void task_b () 
{
  int x = try_lock(m2,m1);
  if (x==-1) 
  {
    std::cout << "task b\n";
    m2.unlock();
    m1.unlock();
  }
  else 
  {
    std::cout << "[task b failed: mutex " << (x?"m1":"m2") << " locked]\n";
  }
}

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

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

  return 0;
}

Output:

task a
[task b failed: mutex m1 locked]

 

 

Write a Comment

Leave a Comment

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