import asyncio
import os
import random
from multiprocessing import Process
process=[]
def cleanup():
global process
while process:
proc=process.pop()
try:
proc.join()
except KeyboardInterrupt:
proc.terminate()
async def worker():
rand=random.randint(0,3)
result=await asyncio.sleep(rand,result="模拟业务时间为{}s".format(rand))
print(result)
def process_main(worker,num):
loop=asyncio.new_event_loop()
try:
workers=[worker() for _ in range(num)]
loop.run_until_complete(asyncio.gather(*workers,loop=loop))
except KeyboardInterrupt:
print(f"stopping {os.getpid()}")
loop.stop()
finally:
loop.close()
def main(process,nums_prop,w_num, process_main):
for _ in range(nums_prop):
proc=Process(target=process_main,args=(worker,w_num))
process.append(proc)
proc.start()
if __name__ == '__main__':
try:
main(process,10,2,process_main)
except KeyboardInterrupt:
print("crtl+c 执行成功,停止进程...")
finally:
cleanup()
|