如何在Python中使用threading.Thread产生其其余部分? [英] How does a threading.Thread yield the rest of its quantum in Python?

查看:67
本文介绍了如何在Python中使用threading.Thread产生其其余部分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在轮询硬件的线程.

I've got a thread that's polling a piece of hardware.

while not hardware_is_ready():
    pass
process_data_from_hardware()

但是还有其他线程(和进程!)可能需要做的事情.如果是这样,我不想消耗CPU检查其他所有指令的硬件.自从我处理线程以来已经有一段时间了,那时我还不是Python,但是我相信大多数线程库都具有yield函数,或者允许线程告诉调度程序的东西给其他线程一个线程".机会."

But there are other threads (and processes!) that might have things to do. If so, I don't want to burn up cpu checking the hardware every other instruction. It's been a while since I've dealt with threading, and when I did it wasn't Python, but I believe most threading libraries have a yield function or something that allows a thread to tell the scheduler "Give the other threads a chance."

while not hardware_is_ready():
    threading.yield()          # This function doesn't exist.
process_data_from_hardware()

但是我在线程文档中找不到对此类内容的任何引用. Python确实有一个yield语句,但是我很确定这完全是另外一回事(与生成器有关).

But I can't find any reference to something like this in the threading documentation. Python does have a yield statement, but I'm pretty sure that's something else entirely (to do with generators).

这里正确的做法是什么?

What's the correct thing to do here?

推荐答案

time.sleep(0)足以进行控制-无需使用正epsilon.实际上,time.sleep(0)意味着屈服于其他可能准备就绪的线程".

time.sleep(0) is sufficient to yield control -- no need to use a positive epsilon. Indeed, time.sleep(0) MEANS "yield to whatever other thread may be ready".

这篇关于如何在Python中使用threading.Thread产生其其余部分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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