我正在尝试使用队列为多线程编写快速事件系统。 每个Thread都有一个stdin并等待这个被填充。
我的主要部分就是这样:
class MyThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.stdin = Queue.Queue()
# Some code here
def run(self):
while True:
try:
order = self.stdin.get(block=True,timeout=5)
if self.do(order) is False:
break
except Queue.Empty:
pass
def do(self,order):
if order["txt"] == "quit":
return False
deltaTime = time.time() - order["time"]
print("Message : "+str(order["txt"])+", DeltaTime : "+str(deltaTime))
# Some code here
我想做快速的多媒体操作,所以我需要一个真正的反应系统,但是当我做一些litle基准测试时,我得到了50毫秒的深度juste(在2.4 GHz Intel i7处理器上)
这是我的基准代码:
thread = MyThread()
thread.start()
thread.stdin.put({"txt": "test1", "time": time.time()})
time.sleep(1)
thread.stdin.put({"txt": "test2", "time": time.time()})
time.sleep(1)
thread.stdin.put({"txt": "test3", "time": time.time()})
time.sleep(1)
thread.stdin.put({"txt": "quit", "time": time.time()})
thread.join()
print("END")
最后我明白了:
Message : test1, DeltaTime : 0.00104689598083
Message : test2, DeltaTime : 0.0151479244232
Message : test3, DeltaTime : 0.0292360782623
END
这大概是20毫秒,但是对于所有程序来说,它对于实时应用程序来说是非常重要的! 现在,当我尝试没有超时时,它会好得多:
Message : test1, DeltaTime : 6.69956207275e-05
Message : test2, DeltaTime : 5.22136688232e-05
Message : test3, DeltaTime : 5.79357147217e-05
END
是否有任何解决方案可以加快Queue.get并保持超时?
谢谢!