Sobes.tech
Middle+

Tell about ways to execute code in Python: multiprocessing, multithreading, asynchronous.

sobes.tech AI

Answer from AI

In Python, there are three main ways to execute code concurrently or asynchronously:

  1. Multiprocessing

    • Uses multiple processes, each with its own memory.
    • Bypasses the GIL (Global Interpreter Lock) limitation, allowing efficient use of multiple CPU cores.
    • Suitable for CPU-intensive tasks.
    • Example:
    from multiprocessing import Pool
    
    def f(x):
        return x*x
    
    with Pool(4) as p:
        print(p.map(f, [1, 2, 3, 4]))
    
  2. Threading

    • Uses multiple threads within a single process.
    • Due to GIL in CPython, only one thread executes Python bytecode at a time.
    • Well-suited for I/O-bound tasks where threads wait for responses.
    • Example:
    import threading
    
    def worker():
        print("Working in a thread")
    
    t = threading.Thread(target=worker)
    t.start()
    t.join()
    
  3. Asyncio

    • Based on an event loop and coroutines.
    • Allows writing non-blocking code, efficiently utilizing waiting time for I/O operations.
    • Does not create new threads or processes, runs in a single thread.
    • Suitable for high-load network applications.
    • Example:
    import asyncio
    
    async def main():
        print('Hello')
        await asyncio.sleep(1)
        print('World')
    
    asyncio.run(main())
    

The choice of method depends on the task: for CPU-intensive tasks — multiprocessing; for I/O-bound tasks — threading or asyncio.