adamlowlife
adamlowlife

Reputation: 239

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.

Upvotes: 2

Views: 903

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36483

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.

Upvotes: 7

Related Questions