1

I saw at concurrency is not parallelism slide that golang can do like this:

func main() {
    go boring("Boring!")
    fmt.Println("I'm listening.")
    time.Sleep(2 * time.Second)
    fmt.Println("You're boring; I'm leaving.")
}

The result look like this

I'm listening.
boring 0
boring 1
boring 2
boring 3
boring 4
boring 5
You're boring; I'm leaving.

Can Python async loop do like this? I'm stuck it at loop.run_forever that it will block the main function:

import asyncio
import random
import time
import itertools


async def boring(msg):
    for i in itertools.count(0):
        print(msg, i)
        await asyncio.sleep(random.random() % 1e3)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    asyncio.ensure_future(boring('boring!'))
    loop.run_forever()
    print('Hello')
    time.sleep(2)
    print('Bye.')
    loop.stop()

It will then run

boring! 0
boring! 1
boring! 2
boring! 3
boring! 4
boring! 5
boring! 6
boring! 7
boring! 8
boring! 9

Can python async loop be async?

2 Answers 2

1

Instead of sleeping after running run_until_complete, you can use timeouts. This way, it would be something like:

async def main():
    print('Hello')
    try:
        await asyncio.wait_for(boring('boring!'), timeout=2.0)
        print('Maybe not that boring!')
    except:
        print('Bye.')

if __name__ == '__main__':
    asyncio.run(main())

This will also automatically cancel the running task when the timeout happens. If you don't want the task to be canceled after timeout, use wait instead of wait_for.

Sign up to request clarification or add additional context in comments.

Comments

0

loop.run_forever() if blocking the execution. As your code is running in a single thread, you need to modify your code to something like this:

async def boring(msg):
    for i in itertools.count(0):
        print(msg, i)
        await asyncio.sleep(random.random() % 1e3)

async def hello(task):
    print('Hello')
    await asyncio.sleep(2)
    print('Bye.')
    task.cancel()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    t = asyncio.ensure_future(boring('boring!'))
    loop.run_until_complete(hello(t))
    loop.stop()

3 Comments

Thanks for the reply, I'm stuck on the last piece about async in Python. If I want to use async in Python, did that mean I will end up my program with a loop.run_until_complete()?
Not sure of what you mean. To execute asynchronous functions you need a run_until_complete or run_forever call that will block the thread for the time being then continue the normal process.
At one point, you have to give up control of a thread to the EventLoop so that it can manage the async stuff. You can think of loop.run_until_complete() and loop.run_forever() as transition between synchronous land and async land.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.