【发布时间】:2019-03-23 19:55:16
【问题描述】:
您能否告诉我这是否是在自己的线程中构建多个独立异步循环的正确方法?
def init():
print("Initializing Async...")
global loop_heavy
loop_heavy = asyncio.new_event_loop()
start_loop(loop_heavy)
def start_loop(loop):
thread = threading.Thread(target=loop.run_forever)
thread.start()
def submit_heavy(task):
future = asyncio.run_coroutine_threadsafe(task, loop_heavy)
try:
future.result()
except Exception as e:
print(e)
def stop():
loop_heavy.call_soon_threadsafe(loop_heavy.stop)
async def heavy():
print("3. heavy start %s" % threading.current_thread().name)
await asyncio.sleep(3) # or await asyncio.sleep(3, loop=loop_heavy)
print("4. heavy done")
然后我正在测试它:
if __name__ == "__main__":
init()
print("1. submit heavy: %s" % threading.current_thread().name)
submit_heavy(heavy())
print("2. submit is done")
stop()
我期待看到1->3->2->4,但实际上是1->3->4->2:
Initializing Async...
1. submit heavy: MainThread
3. heavy start Thread-1
4. heavy done
2. submit is done
我认为我在理解异步和线程方面遗漏了一些东西。
线程不同。我为什么要在MainThread 里面等到Thread-1 里面的工作完成?
【问题讨论】:
标签: python-3.x python-asyncio python-multithreading