Mis a jour le 2022-09-03, 19:38

asyncio

coroutine :
Fonctions disponibles :
Exemple avec gather :
import asyncio
async def f1():
    print('start f1')
    await asyncio.sleep(1)
    print('end f1')
    return 2

async def f2():
    print('start f2')
    await asyncio.sleep(5)
    print('end f2')
    return 10
    
async def f3():
    print('start f3')
    await asyncio.sleep(2)
    print('end f3')
    return 4
    
async def g():
    result = await asyncio.gather(f1(), f2(), f3())
    return result

result = asyncio.run(g())
print(result)
  
donne
start f1
start f2
start f3
end f1
end f3
end f2
[2, 10, 4]
  
Exemple avec create_task :
import asyncio

async def f1():
    print('start f1')
    await asyncio.sleep(1)
    print('end f1')

async def f2():
    print('start f2')
    await asyncio.sleep(5)
    print('end f2')
    
async def f3():
    print('start f3')
    await asyncio.sleep(2)
    print('end f3')
    
async def g():
    t1 = asyncio.create_task(f1())
    t2 = asyncio.create_task(f2())
    t3 = asyncio.create_task(f3())

    await asyncio.wait([t1, t2, t3])

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
asyncio.run(g())
  

Copyright python-simple.com
programmer en python, tutoriel python, graphes en python, Aymeric Duclert