python threading.Event:添加事件参数(python threading.Event: add event params)

系统教程 行业动态 更新时间:2024-06-14 17:03:54
python threading.Event:添加事件参数(python threading.Event: add event params)

我是否可以使用来自线程模块的Event对象,不仅可以通知某些事件已发生,还可以提供此事件的一些参数,例如:

e = Event() ... e.param = "this is event data" e.set()

另一个线程:

e.wait() data = e.param

乍一看似乎没问题,但是有什么问题可以发生吗? 安全吗? 如果没有,还有什么方法可以更好地在线程之间传递一些事件参数?

感谢名单。

Can I use Event object from threading module not only to notify that some event has happened but also to give some params of this event, for example:

e = Event() ... e.param = "this is event data" e.set()

Another thread:

e.wait() data = e.param

It seems to be ok at first glance, but are there any problems than can happen? Is it safe? If not, what other way is better to pass some events params between threads?

Thanx.

最满意答案

您实际上不需要将值附加到Event对象,您可以使用与Event分开的其他全局,属性等,并使用Event来表示它已更新。 这是通常的做事方式。

但是你所做的事情真的没什么不对 。 除了使用信号事件的常规竞争问题之外,它不会增加任何其他问题。 然而,它似乎有点误导 - 它使得看起来好像param以某种方式同步,而不是。

如果您尝试发信号通知新值已准备好,并且同步对该值的访问,则几乎总是需要Condition ,如下所示:

c = Condition() data = None ... with c: data = "new data" c.notify() ... with c: while data is None: c.wait()

或者,更简单地说,只是使用queue而不是首先共享变量:

q = Queue() ... q.put(data) ... data = q.get()

You don't really need to attach the value to the Event object, you can just use some other global, attribute, etc. separate from the Event, and use the Event to signal that it's been updated. And that's the usual way of doing things.

But there's really nothing wrong with what you're doing. And it doesn't add any other problems beyond the usual race problems with using events for signaling. However, it does seem a bit misleading—it makes it seem as if the param is somehow synchronized, when it isn't.

If you're trying to signal that a new value is ready, and synchronize access to that value you almost always want a Condition, like this:

c = Condition() data = None ... with c: data = "new data" c.notify() ... with c: while data is None: c.wait()

Or, more simply, just use a queue and don't share a variable in the first place:

q = Queue() ... q.put(data) ... data = q.get()

更多推荐

本文发布于:2023-04-24 14:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/1c4b5aec76e690811f881c450ecae94a.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   事件   Event   python   threading

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!