threading.Condition与threading.Event [英] threading.Condition vs threading.Event

查看:214
本文介绍了threading.Condition与threading.Event的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我还没有在 threading 模块中找到关于ConditionEvent类之间差异的清晰解释.是否有一个明确的用例,其中一个比另一个更有用?我可以找到的所有示例都使用生产者-消费者模型作为示例,其中queue.Queue是更直接的解决方案.

I have yet to find a clear explanation of the differences between Condition and Event classes in the threading module. Is there a clear use case where one would be more helpful than the other? All the examples I can find use a producer-consumer model as an example, where queue.Queue would be the more straightforward solution.

推荐答案

简而言之,当线程有兴趣等待某些事情变为真时,便使用条件; 一旦它变为真,便可以独占访问某些内容共享资源.

Simply put, you use a Condition when threads are interested in waiting for something to become true, and once its true, to have exclusive access to some shared resource.

当线程仅对等待某些事情变为真感兴趣时,使用Event.

Whereas you use an Event when threads are just interested in waiting for something to become true.

从本质上讲,Condition是抽象的Event + Lock,但是当您考虑可以在同一个基础锁上具有多个不同的Condition时,它将变得更加有趣.因此,您可以使用不同的条件来描述基础资源的状态,这意味着您可以唤醒仅对共享资源的特定状态感兴趣的工作器.

In essence, Condition is an abstracted Event + Lock, but it gets more interesting when you consider that you can have several different Conditions over the same underlying lock. Thus you could have different Conditions describing the state of the underlying resource meaning you can wake workers that are only interested in particular states of the shared resource.

这篇关于threading.Condition与threading.Event的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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