睡觉的Python线程怎么最好? [英] How best to wake a sleeping Python thread?

查看:170
本文介绍了睡觉的Python线程怎么最好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的LAN上有一个仪器,每5-10ms发送一个UDP数据包。在我的应用程序中,我有一个读取器线程,在启动时为其分配一个大缓冲区的套接字,然后进入无限循环以读取累积的数据包,解析它们,将它们写入后台处理程序,然后再睡眠半秒( time.sleep(0.500))。

There's an instrument on my LAN that sends a UDP data packet every 5-10 ms. In my application, I have a reader thread that allocates a socket with a large buffer when it starts, then enters an infinite loop to read the accumulated packets, parse them, write them to a spooler, then sleep for half a second (time.sleep(0.500)).

我有几个懒惰的消费者的数据,其中大部分是归档或生成被动统计。但是一个消费者(用于显示)需要最新的数据,并且在查询假脱机程序之前需要唤醒睡眠阅读器(以读取套接字)。

I have several lazy consumers for the data, most of which do archiving or generate passive statistics. But one consumer (for display) needs up-to-the-moment data, and needs to wake the sleeping reader (to read the socket) before querying the spooler.

唤醒睡眠线程的最佳方法是什么?

What is the best way to wake a sleeping thread?

(或者,线程睡眠有更好的方法吗?)

(Or, alternately, is there a better way for a thread to sleep that's easier to wake?)

推荐答案

我没有注意到threading.condition.wait()有一个可选的超时参数!

I had failed to notice that threading.condition.wait() has an optional timeout argument!

答案是创建条件对象,并使用其 wait()方法与可选的超时而不是 time.sleep()。如果线程需要在超时之前被唤醒,请调用通知()条件对象的方法。

The answer is to create a condition object and use its wait() method with the optional timeout instead of time.sleep(). If the thread needs to be woken prior to the timeout, call the notify() method of the condition object.

这篇关于睡觉的Python线程怎么最好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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