Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is unique_lock unlocked when a function is called?

Let's say I have a situation like this:

void consumer(){
   unique_lock<mutex> lock(mtx);
   foo();  
}

void foo(){
    /* does the thread still own the mutex here? */
}

I expect it does but I'm not 100% sure.

like image 452
adamlowlife Avatar asked Dec 09 '25 09:12

adamlowlife


1 Answers

The destructor of unique_lock calls mtx.unlock(). The destructor is called at the end of the lifetime of the lock. Generally (see comments), the end of the lifetime of the lock is :

void consumer(){
   unique_lock<mutex> lock(mtx);
   foo();  
} // <- here.

So yes, it'll still be locked.

like image 156
Hatted Rooster Avatar answered Dec 11 '25 00:12

Hatted Rooster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!