我使用python将一个硬件usb嗅探器设备与供应商提供的pythonapi接口,并尝试在一个无限循环的单独线程中从该设备读取(usb包)(这很好)。问题是我的主循环似乎再也不会被调度(我的read循环得到了所有的关注)。在
代码看起来很像:from threading import Thread
import time
usb_device = 0
def usb_dump(usb_device):
while True:
#time.sleep(0.001)
packet = ReadUSBDevice(usb_device)
print "packet pid: %s" % packet.pid
class DumpThread(Thread):
def run(self):
usb_dump()
usb_device = OpenUSBDevice()
t = DumpThread()
t.start()
print "Sleep 1"
time.sleep(1)
print "End"
CloseUSBDevice(usb_device)
sys.exit(0)
(我可以粘贴实际的代码,但由于您需要硬件设备,所以我认为这不会有太大帮助)。在
我希望在主线程终止整个程序之前,这段代码将开始转储usb包大约一秒钟。然而,我看到的只是“sleep1”,然后usb_dump()过程将永远运行。如果我取消注释“时间。睡觉usb_dump()过程内部循环中的(0.001)“语句开始以我预期的方式工作,但是python代码就无法跟上所有传入的包:-(
供应商告诉我这是python调度程序的问题,而不是他们的api的错,因此对我没有帮助:«However, it seems like you are experiencing some nuances when using threading in Python. By putting the time.sleep in the DumpThread thread, you are explicitly signaling to the Python threading system to give up control. Otherwise, it is up the Python interpreter to determine when to switch threads and it usually does that after a certain number of byte code instructions have been executed.»
有人能确认python是这里的问题吗?有没有其他方法使DumpThread释放控制?还有别的主意吗?在