【发布时间】:2019-05-21 11:39:52
【问题描述】:
Python 3.6.6
代码如下:
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor
executor_processes = ProcessPoolExecutor(2)
def calculate():
while True:
print("while")
time.sleep(1)
async def async_method():
loop_ = asyncio.get_event_loop()
loop_.run_in_executor(executor_processes, calculate)
await asyncio.sleep(1)
print("finish sleep")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(async_method())
print("main_thread is finished")
输出:
同时
完成睡眠
main_thread 已完成
而
而
...
我希望子进程将被终止,就像使用守护进程属性生成进程时一样:
import asyncio
import time
import multiprocessing
def calculate():
while True:
print("while")
time.sleep(1)
async def async_method():
proc = multiprocessing.Process(target=calculate)
proc.daemon = True
proc.start()
await asyncio.sleep(1)
print("finish sleep")
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(async_method())
print("main_thread is finished")
输出:
同时
完成睡眠
main_thread 已完成
问题:如何将loop_.run_in_executor(executor_processes, calculate) 的行为改为“类似守护进程”?
【问题讨论】:
标签: python python-3.x python-multiprocessing python-asyncio