我正在尝试在线程中运行asyncio。我这样做的原因是,我想从非异步主线程与asyncio通信。 这是我的代码
import asyncio
import threading
async def consume(input_q, output_q):
while True:
item = await input_q.get()
print(item)
output_q.put("hello back")
async def run(input_q, output_q):
asyncio.ensure_future(consume(input_q, output_q))
while True:
await asyncio.sleep(1)
print("message")
def run_in_thread(loop,input_q,output_q):
asyncio.set_event_loop(loop)
loop.run_until_complete(run(input_q, output_q))
loop = asyncio.new_event_loop()
input_q = asyncio.Queue(loop=loop)
output_q = asyncio.Queue(loop=loop)
thread = threading.Thread(target=run_in_thread ,args=(loop, input_q, output_q))
thread.start()
time.sleep(5)
asyncio.run_coroutine_threadsafe(input_q.put("hello input"), loop)
time.sleep(2)
item = asyncio.run_coroutine_threadsafe(output_q.get_nowait(), loop).result()
assert "hello back" in item
print(item)
loop.call_soon_threadsafe(loop.stop)
thread.join()
我能够将消息从主线程放入输入队列。不幸的是,包子无法从output_q中读取。有什么解决办法吗? 在此行得到错误:
item = asyncio.run_coroutine_threadsafe(output_q.get_nowait(), loop).result()
--> raises QueueEmpty
也许使用多处理或其他方法。我想做的是运行上述功能,并从另一个不使用异步的进程或线程与它们进行通信。非常感谢您提供任何提示!
PS:我正在使用python 3.5