并行任务concurrent.futures和Coroutines

import time
from concurrent.futures import ProcessPoolExecutor

def print_hello():
    while True:
        print('sleep 1')
        time.sleep(1) 


def print_goodbye():
    while True:
        print('sleep 2')
        time.sleep(2) 
        
with ProcessPoolExecutor(max_workers=2) as e:
     e.submit(print_hello)
     e.submit(print_goodbye)

哪个更好

import asyncio

async def print_hello():
    while True:
        print('sleep 1')
        await asyncio.sleep(1) 


async def print_goodbye():
    while True:
        print('sleep 2')
        await asyncio.sleep(2) 


co1 = print_hello()  
co2 = print_goodbye()  
asyncio.get_event_loop().run_until_complete(asyncio.gather(co1, co2))   

asyncio.run(main()) 比 asyncio.get_event_loop().run_until_complete 更简洁

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注