Sobes.tech
Junior — Middle

Can you list types of parallel and concurrent programming implemented in Python?

sobes.tech AI

Answer from AI

Python implements several types of parallel and concurrent programming:

  1. Multithreading — allows running multiple threads within a single process. Due to GIL (Global Interpreter Lock) in CPython, threads cannot execute bytecode simultaneously, but are suitable for I/O-bound tasks.

  2. Multiprocessing — creates multiple processes, each with its own memory, which helps bypass the GIL limitation and efficiently utilize multiple CPU cores.

  3. Asynchronous programming (asyncio) — based on an event loop and coroutines, allows writing concurrent code without threads and processes, effective for IO-bound tasks.

  4. Concurrent Futures — a high-level interface for running tasks in threads or processes via ThreadPoolExecutor and ProcessPoolExecutor.

Example of using 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 of asyncio:

import asyncio

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

asyncio.run(say_hello())