#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
Couple of things:
std::unique_lock ul
object only ever gets destroyed at the end offunc
scope. When you throw the exception and catch it only objects withintry ... catch
block get destroyed, butul
is defined outside that block and, hence, it doesn't get destroyed.des == "T1"
compares string pointers, not string contents. It may or may not yieldtrue
whendes
points to stringT1
. You should compare C-style strings withstd::strcmp
, e.g.!std::strcmp(des, "T1")
.