简体   繁体   English

在while(1)循环中增强互斥锁上的scoped_lock

[英]boost scoped_lock on mutex in while(1) loop

I have 2 processes which share a queue which is synchronized by a mutex and conditions. 我有2个进程共享一个由互斥量和条件同步的队列。 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? 我的问题是,互斥是否在while循环中的所有调用中都具有作用域,还是每次while循环开始时都需要获取互斥体? 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. 似乎每次在while循环结束时,互斥体都被解锁。

Thanks 谢谢

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. 在这种情况下,它将在每次迭代中锁定和解锁互斥锁一次。

A scoped_lock , as the name suggests, locks a mutex on creation (in its ctor) and unlocks it on deletion (in its dtor). 顾名思义, scoped_lock在创建时(在其ctor中)锁定互斥锁,在删除时(在其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. 由于lock实例的作用域在while主体内,因此互斥锁会在创建scoped_lock时锁定,并在while循环结束时解锁:应该找到breakcontinue ,甚至找到return语句,或者只是在结束时while身体到达时,每个循环一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM