If exception occurred unique lock will unlock the mutex

401 views Asked by At
#include <iostream>
#include <vector>
#include <thread>
#include<mutex>
using namespace std;
mutex m;
int count;
void
func (const char *des)
{
  std::unique_lock < mutex > ul (m);
  cout << "in :" << des << endl;
  try
  {
    if (des == "T1")
      throw "T1";
  }
  catch ( ...)
  {
    cout << "catched" << endl;
  }
  this_thread::sleep_for (10 s);
  cout << "out of func" << endl;
}

int
main ()
{

  // Constructing two threads and run it. Does not block execution.
  thread t1 (func, "T1");
  thread t2 (func, "T2");

  cout << "main, t1 and t2 functions now execute concurrently...\n";

  // synchronize threads
  t1.join ();           // Makes the main thread wait until t1 finishes
  t2.join ();           // Makes the main thread wait until t2 finishes
}

Expecting Output: in T1 exception catched T1 going to waiting state in T2(because unique lock will unlock the mutex So T2 can start working with out T1 completing the task) in :T2 out of func out of func

current output: in T1 exception catched T1 going to waiting state out of func in :T2 out of func

why tread 2 waiting for completion of thread 1 even exception occurred

1

There are 1 answers

0
Maxim Egorushkin On

Couple of things:

  1. That std::unique_lock ul object only ever gets destroyed at the end of func scope. When you throw the exception and catch it only objects within try ... catch block get destroyed, but ul is defined outside that block and, hence, it doesn't get destroyed.
  2. des == "T1" compares string pointers, not string contents. It may or may not yield true when des points to string T1. You should compare C-style strings with std::strcmp, e.g. !std::strcmp(des, "T1").