I am learning to use c++
lock_guard
. Online resources say that we do not need to unlock
manually and secondly in the case of an exception the mutex
is automatically released so that other threads can proceed.
I am trying to find an example for the second case. Basically, I am trying to find use case when one thread gets an exception then the other thread should continue.
std::mutex m;
void f1() {
lock_guard<std::mutex> lock(m);
// some task that may raise exception
}
void f2() {
lock_guard<std::mutex> lock(m);
// some other task
}
int main() {
std::thread T1(f1);
T1.detach();
std::thread T2(f2);
T2.join();
}
I tried with divided by zero arithmetic inside f1
. But it crashes the whole program. Then I tried with allocating a very large memory (for example new int[100000000000]
) inside f1
. Then also the whole program crashed saying bad_alloc
.
std::mutex m;
int a,b;
void f1() {
lock_guard<std::mutex> lock(m);
a = 1;
int * ptr = new int[10000000000]; // too large
b = 2;
}
void f2() {
lock_guard<std::mutex> lock(m);
cout << a <<" : "<<b <<endl;
}
int main() {
std::thread T1(f1);
T1.detach();
std::thread T2(f2);
T2.join();
}
error:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
If I use try-catch block around the problematic code segment, then thread2
executes and the program does not terminate abruptly. But now T1
does not release the lock(as expected from try catch block
).
std::mutex m;
int a,b;
void f1() {
lock_guard<std::mutex> lock(m);
a = 1;
try {
int * ptr = new int[10000000000];
}catch(...) {
cout <<"new faild"<<endl;
}
// still locked
std::this_thread::sleep_for(std::chrono::milliseconds(2000)); //2s
b = 2;
}
void f2() {
lock_guard<std::mutex> lock(m);
cout << a <<" : "<<b <<endl;
}
int main() {
std::thread T1(f1);
T1.detach();
std::thread T2(f2);
T2.join();
}
I am also not convinced with the try-catch block
in the above situation because of the whole point of not using mutex.lock()/unlock()
was to gracefully handle and releasing of the mutex.
Am I missing something? Please give one example where an exception occurs (some common exception cases) in one thread and the mutex is released and other threads continue to execute. Also, the main program should also not terminate.
Thanks!