-3

I need to run two python functions simultaneously. How can I achieve that? Example:

import time
def short_task():
  time.sleep(2)

def long_task():
  time.sleep(4)

short_task()
long_task()

I expect the whole code to finish in 4 seconds (instead of 6).

Johann Lau
  • 173
  • 1
  • 15

2 Answers2

2

It depends on what the functions are doing.

If it is something that involves waiting (such as time.sleep() or waiting for a response) use a Thread.

import time
from threading import Thread

def short_task():
  time.sleep(2)

def long_task():
  time.sleep(4)

Thread(target=short_task).start()
Thread(target=long_task).start()

If you have a long task that requires a lot of computing, use a Process:

import time
from multiprocessing import Process

def short_task():
  time.sleep(2)

def long_task():
  time.sleep(4)

if __name__ == '__main__':
    Process(target=short_task).start()
    Process(target=long_task).start()
big_bad_bison
  • 1,021
  • 1
  • 7
  • 12
1

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.

Johann Lau
  • 173
  • 1
  • 15
  • 1
    This will achieve the desired result only for nonblocking asynchronous calls (e.g., async-sleep). For CPU-bound or otherwise blocking calls you will probably again end up with sequential execution. – moooeeeep Feb 04 '21 at 13:28
  • I don't think you need blocking calls. Just replace all `time.sleep` with `asyncio.sleep` and you are cool. – Johann Lau Feb 04 '21 at 13:33