how to write a simple Python Multi-thread task

Solution 1:

If you use asyncio, you should use asyncio.sleep instead of time.sleep because it would block the asycio event loop. here is a working example:

import asyncio


async def foo():
    print("Waiting...")
    await asyncio.sleep(5)
    print("Done waiting!")


async def bar():
    print("Hello, world!")


async def main():
    t1 = asyncio.create_task(foo())
    await asyncio.sleep(1)
    t2 = asyncio.create_task(bar())

    await t1, t2


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

In this example, foo and bar run concurrently: bar does execute while foo also do.