Reputation: 185
I have 2 processes which share a queue which is synchronized by a mutex and conditions. I have the following code in one of my processes.
named_mutex mutex(open_only, "MyMutex");
int main()
{
while(1)
{
scoped_lock <named_mutex> lock(mutex)
//do some processing
}
}
My question is whether the mutex has scope throughout all calls in the while loop or does it need to be acquired each time the while loop starts? What is the scope of the mutex for it to be unlocked? It seems each time at the end of the while loop the mutex is unlocked.
Thanks
Upvotes: 3
Views: 1776
Reputation: 777
A scoped_lock
, as the name suggests, locks a mutex on creation (in its ctor) and unlocks it on deletion (in its dtor).
Since the scope of the lock
instance is within the while
body, the mutex is locked when the scoped_lock
is created, and unlocked whenever the while
loop ends: should a break
or continue
, or even a return
statement be found, or simply when the end of the while
body is reached, once for each loop.
Upvotes: 0
Reputation: 96241
It behaves exactly the same as any other local variable within a loop body: It will be created and destroyed once per itereation. In this case it will lock and unlock the mutex once per iteration.
Upvotes: 10