在 while 循环检查中处理互斥变量
如果在一个线程中修改并使用互斥体正确锁定和解锁的变量在另一个线程的 while 循环中读取,如何锁定和解锁互斥体以便 while 循环可以读取该值,是否有必要?
我在一个线程中设置一个变量,并使用 while 循环在另一个线程中检查它。如何锁定和解锁变量以检查 while 循环条件?
唯一合理的方法是使用一个附加变量来运行 while 循环并将其设置为需要锁定/解锁的变量的值吗?
If a variable that is being modified in a thread and is properly locked and unlocked using a mutex is read in a while loop in another thread how does one lock and unlock the mutex so that the while loop can read the value, is it even necessary?
I set a variable in a thread and check it in another thread using a while loop. How is the variable locked and unlocked for checking in the while loop condition?
Is the only reasonable way to do it, to have an additional variable that is used to run the while loop and set that to the value of the variable that needs locking/unlocking?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
编辑:@ninjalj 建议使用条件变量替换
while
循环,这是一个好建议,如果您正在使用while
-循环等待直到达到程序状态。但是,如果您使用 while 循环来执行工作,直到达到程序状态,那么...您应该包装“
lock-mutex;”检查变量;解锁互斥体”实用函数中的代码,然后您的 while 循环条件可以调用该函数。例如,实用程序函数可以编写为以下代码所示:
然后,您的
while
循环条件可以编写如下:Edit: @ninjalj's suggestion to replace the
while
-loop with use of a condition variable is good advice if you are using thewhile
-loop to wait until a program state has been reached. However, if you are using awhile
-loop to do work until a program state has been reached then...You should wrap the "
lock-mutex; examine variable; unlock mutex
" code in a utility function, and yourwhile
-loop condition can then call that function. For example, the utility function might be written as shown in the following code:Then, your
while
-loop condition can be written like the following:您可能应该使用条件变量。请参见 pthread_cond_wait(3) 和 pthread_cond_signal(3)
You should probably use a condition variable. See
pthread_cond_wait(3)
andpthread_cond_signal(3)
如果有丝毫可能其他人同时写入,则必须在读取期间锁定它。否则,可能会发生各种情况,例如您看到部分更新或根本没有更新。
如果您使用该值作为循环条件,并且在循环期间不受更新的影响,则制作副本并释放锁可能是一个好主意。如果您会受到更改的影响,您当然必须保持锁定。
You must lock it during the read, if there is the slightest chance someone else is writing at the same time. Otherwise all kinds of things could happen, like you seeing a partial update or no update at all.
If you use the value as a loop condition, and are not affected by updates during the loop, making a copy and release the lock could be a good idea. If you would be affected by a change, you will have to keep the lock of course.