Comment

Comment by BiteCode_dev

I get that this guide tries to ease you in into low level concurrency concepts.

However, if you try to just get work done in Python, this is not what you want.

Don't do threads/processes yourself, use pools:

    import random
    import time
    from concurrent.futures import ProcessPoolExecutor, as_completed

    def hello():
        seconds = random.randint(0, 5)
        print(f"Start blocking for {seconds}s")
        time.sleep(seconds)
        print(f"Stopped blocking after {seconds}s")
        return seconds

    if __name__ == "__main__":

        with ProcessPoolExecutor(max_workers=2) as exec:

            a = exec.submit(hello)
            b = exec.submit(hello)

            for future in as_completed((a, b)):
                print(future.result())
And don't manage the loop yourself. Use Python 3.7, and replace:

    loop = asyncio.get_event_loop()
    loop.run_until_complete(loop.create_task(foo()))
    loop.close()
With: asyncio.run(foo())

The code is not just shorter, it is way, wayyyyyyyyyyyy, more correct.

Also don't program asyncio by hand. Use a lib. E.G: wanna do http, use aiohttp.

This is Python, don't suffer more than you need to.

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton