Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

319
Visualizações
Python asyncio: how are tasks scheduled?

I'm new to Python asyncio and I'm doing some experiments. I have the following code:

async def say_after(n, s):
    await asyncio.sleep(n)
    print(s)

async def main():
    task1 = asyncio.create_task(say_after(2, 'a'))
    task2 = asyncio.create_task(say_after(1, 'b'))
    await task1
    print('x', flush=True)
    await task2
    print('y', flush=True)

asyncio.run(main())

And the output:

b
a
x
y

I don't understand the order here. Can someone help explain? Especially why x comes after b and a?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Especially why x comes after b and a?

b is printed in task2 about 1 second after the start of main, and a is printed in task1 about 2 seconds after the start of main. The await task1 waits for task1, and so waits about 2 seconds. So by the time await task1 completes, both b and a would have been printed.

(The "about"s in the above are deliberate... there would be variations, but in most situations, they would be small)

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda