DEV Community

Dendi Handian
Dendi Handian

Posted on • Edited on

Simulating Paralel Processing in Python using AsyncIO

Here is a simple simulation of how to run multiple process (or simply a function) in paralel using AsyncIO

from time import sleep, time
import asyncio

def delay(seconds):
  """
  A normal function that simulates a blocking operation.
  """
  print(f"Starting delay for {seconds} seconds.")
  sleep(seconds)
  print(f"Finished delay for {seconds} seconds.")
  return f'sleep for {seconds} second(s)'


async def main():
  start_time = time()
  loop = asyncio.get_running_loop()

  # Schedule the blocking functions to run in the default thread pool executor
  # run_in_executor returns a future that we can await
  tasks = [loop.run_in_executor(None, delay, seconds) for seconds in [3, 6, 9]]

  # Now we await all the tasks to run concurrently
  print("Waiting for all tasks to complete...")
  results = await asyncio.gather(*tasks)

  print(f'results: ', str(results))

  end_time = time()
  print("\n--- All tasks are done! ---")
  print(f"Results: {results}")
  print(f"Total time: {end_time - start_time:.2f} seconds")

if __name__ == "__main__":
    asyncio.run(main())
Enter fullscreen mode Exit fullscreen mode

Top comments (0)