我有两个异步事件循环在两个不同的线程中运行。
Thread1通过异步队列()。在
其中一个线程引发异常:got Future attached to a different loop
现在这是真的,因为我有一个队列,我在不同的循环中使用。如何在两个不同线程的两个循环之间共享队列?
示例代码:q = asyncio.Queue()
async def producer(q):
await asyncio.sleep(3)
q.put(1)
def prod_work(q):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(producer(q))
async def consumer(q):
await asyncio.sleep(3)
res = await q.get()
def cons_work(q):
loop2 = asyncio.new_event_loop()
asyncio.set_event_loop(loop2)
loop2.run_until_complete(consumer(q))
def worker(q):
# main thread - uses this threads loop
prod = threading.Thread(target=prod_work, args=(q,))
# separate thread - uses NEW loop
cons = threading.Thread(target=cons_work, args=(q,))
prod.start()
cons.start()
worker(q)
完整堆栈跟踪:
^{pr2}$