One of your options is to use the asyncio module.
First of all, import the asyncio module with import asyncio
. Replace your def
functions to async def
functions.
Second of all, replace time.sleep()
with await asyncio.sleep()
. You no longer need the time module because of this step.
Thirdly, create a new function, normally called main()
. You can take the following code snippet for reference:
async def main():
task1 = asyncio.create_task(
short_task())
task2 = asyncio.create_task(
long_task())
await task1
await task2
Finally, run the whole main()
code with asyncio.run(main())
. Your final code should look like this:
import asyncio
async def short_task():
await asyncio.sleep(2)
async def long_task():
await asyncio.sleep(4)
async def main():
task1 = asyncio.create_task(
short_task())
task2 = asyncio.create_task(
long_task())
await task1
await task2
You may use a simple code snippet to proof that the whole process took 4 seconds.