cocojim
cocojim

Reputation: 403

how to write a simple Python Multi-thread task

I have the below simple functions:

import time

def foo():
    print(f'i am working come back in 5mins')
    time.sleep(300)

def boo():
    print(f' boo!')

def what_ever_function():
    print(f'do whatever function user input at run time.')

What I wish to do is execute foo() and then immediately execute boo() or what_ever_function() without having to wait for 300 seconds for foo() to finish.

Imagine a workflow in Ipython:

>>> foo()
i am working come back in 5mins
>>> boo()
boo!

The idea is after execute foo(), I can use the user-prompt to run another function immediately; whatever function that may be; without having to wait 300 seconds for foo() to finish.

I already tried googleing: https://docs.python.org/3/library/asyncio.html and https://docs.python.org/3/library/threading.html#

But still couldn't achieve the above task.

Any pointer or help please?

Thanks

Upvotes: 0

Views: 49

Answers (1)

Louis Lac
Louis Lac

Reputation: 6436

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.

Upvotes: 1

Related Questions