Sobes.tech
Junior — Middle

What methods are used for parallel task execution in Python?

sobes.tech AI

Answer from AI

In Python, there are several approaches for parallel task execution:

  1. Multithreading — allows running multiple threads within a single process. Useful for I/O-bound tasks, but inefficient for CPU-bound tasks due to the GIL (Global Interpreter Lock).

  2. Multiprocessing — creates multiple processes, each with its own memory, bypassing the GIL limitation. Suitable for CPU-bound tasks.

  3. Asynchronous programming (asyncio) — enables writing non-blocking code that waits for I/O operations using an event loop and coroutines.

Example with multiprocessing:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(4) as p:
        print(p.map(f, [1, 2, 3, 4]))

Example with asyncio:

import asyncio

async def say_hello():
    await asyncio.sleep(1)
    print('Hello')

async def main():
    await asyncio.gather(say_hello(), say_hello())

asyncio.run(main())