[英]How to communicate between traditional thread and asyncio thread in Python?
[英]How to communicate with worker thread
我正在使用大量使用I / O的库。 因此,对该库的调用可能会持续很长时间(超过5秒)。 在UI
中直接使用它不是一个好主意,因为它将冻结。
因此,我将库调用外包到线程队列,如本例所示: Python线程:通信和停止
不过,我对此解决方案并不满意,因为这有一个主要缺点:
每个lib命令都返回一条返回消息,该返回消息可以是错误消息或某些计算结果。 我怎么得到这个?
考虑一个库调用do_test(foo)
:
def do_test(foo):
time.sleep(10)
return random.random() * foo
def ui_btn_click():
threaded_queue.put((do_test, 42))
# Now how to display the result without freezing the UI?
有人可以给我建议如何实现这种模式吗?
编辑:这是一个最小的示例:
import os, time, random
import threading, queue
CMD_FOO = 1
CMD_BAR = 2
class ThreadedQueue(threading.Thread):
def __init__(self):
super().__init__()
self.in_queue = queue.Queue()
self.out_queue = queue.Queue()
self.__stoprequest = threading.Event()
def run(self):
while not self.__stoprequest.isSet():
(cmd, arg) = self.in_queue.get(True)
if cmd == CMD_FOO:
ret = self.handle_foo(arg)
elif cmd == CMD_BAR:
ret = self.handle_bar(arg)
else:
print("Unsupported cmd {0}".format(cmd))
self.out_queue.put(ret)
self.in_queue.task_done()
def handle_foo(self, arg):
print("start handle foo")
time.sleep(10)
return random.random() * arg
def handle_bar(self, arg):
print("start handle bar")
time.sleep(2)
return (random.random() * arg, 2 * arg)
if __name__ == "__main__":
print("START")
t = ThreadedQueue()
t.start()
t.in_queue.put((CMD_FOO, 10))
t.in_queue.put((CMD_BAR, 10))
print("Waiting")
while True:
x = t.out_queue.get(True)
t.out_queue.task_done()
print(x)
我个人使用PySide
但我不想将此库依赖于PySide
或任何其他与ui相关的库。
我对自己的实现做了一些思考。 结论是,我启动了另一个线程来选择队列结果:
class ReceiveThread(threading.Thread):
"""
Processes the output queue and calls a callback for each message
"""
def __init__(self, queue, callback):
super().__init__()
self.__queue = queue
self.__callback = callback
self.__stoprequest = threading.Event()
self.start()
def run(self):
while not self.__stoprequest.isSet():
ret = self.__queue.get(True)
self.__callback(ret)
self.__queue.task_done()
来自UI或其他位置的给定回调将与队列中的每个结果一起调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.