pthread_cond_wait和互斥体要求 [英] pthread_cond_wait and mutex requirement

查看:102
本文介绍了pthread_cond_wait和互斥体要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在调用pthread_cond_wait之前需要锁定互斥锁?

Why it is required to lock a mutex before calling pthread_cond_wait?

此外,在调用pthread_cond_signal之前是否需要在同一互斥锁上进行锁定?

Also, is it required to take a lock (on the same mutex) before calling pthread_cond_signal?

感谢您的帮助.

推荐答案

为什么在调用pthread_cond_wait之前需要锁定互斥锁?

Why it is required to lock a mutex before calling pthread_cond_wait?

因为否则会有不可避免的比赛条件.

Because otherwise there is an unavoidable race condition.

互斥锁可保护共享状态.条件变量与状态上的某些谓词(条件")相关联.基本思想是您想要:

A mutex protects shared state. A condition variable is associated with some predicate ("condition") on the state. The basic idea is that you want to:

1)检查谓词

2)如果谓词为假,请睡觉直到它变为真

2) if the predicate is false, go to sleep until it becomes true

在并发系统中,某些线程总是有可能在(1)和(2)之间使谓词为真.为了避免这种竞争,必须在(1)之前持有一个互斥锁,并且在执行(2)时必须自动释放它.

In a concurrent system, it is always possible for some thread to make the predicate true between (1) and (2). To avoid this race, you must hold a mutex before (1) and you must release it atomically as you perform (2).

例如,对于队列,谓词可能为队列不为空".但是在您检查队列是否为非空的时间与您进入睡眠的时间之间,某些其他线程可能会在队列中添加一些内容.

For example, for a queue the predicate might be "the queue is not empty". But between the time you check to see if the queue is non-empty and the time you go to sleep, some other thread might add something to the queue.

因此,在检查谓词时以及在调用pthread_cond_wait时,都必须保持互斥锁.

Thus you must hold the mutex both while checking the predicate and at the time you call pthread_cond_wait.

而且,在调用pthread_cond_signal之前是否需要在同一互斥锁上进行锁定?

Also, is it required to take a lock (on the same mutex) before calling pthread_cond_signal?

据我所知,这没有根本问题;它只会带来潜在的低效率.

To my knowledge, there is no fundamental problem with this; it just introduces potential inefficiencies.

这里,您正在修改的任何共享状态(因此使谓词为true)都必须由互斥量保护.因此,只要您想要发信号通知情况,您就必须已经持有互斥体.

Here again, whatever shared state you are modifying (and thus making the predicate true) has to be protected by a mutex. So any time you want to signal the condition you must already hold the mutex anyway.

如果在发出条件信号之前释放互斥锁,则由于其他线程的作用,谓词有可能在其间变为假.这场比赛不会导致失败,因为任何等待条件的线程都必须在继续操作之前仔细检查该谓词...但是为什么要解决这个麻烦呢?

If you release the mutex before signaling the condition, it is possible for the predicate to become false in between due to the action of some other thread. This race does not cause failures because any thread waiting on the condition must double-check the predicate anyway before proceeding... But why put it through the trouble?

底线:只需按照说明进行操作,您甚至不必考虑这些问题. :-)

Bottom line: Just follow the instructions and you do not even have to think about these questions. :-)

这篇关于pthread_cond_wait和互斥体要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆