Low Orbit Flux Logo 2 F

Python Multitasking

CPU Bound Multi Processing
I/O Bound, Fast I/O, Limited Number of Connections Multi Threading
I/O Bound, Slow I/O, Many connections Asyncio


if io_bound:
    if io_very_slow:
        print("Use Asyncio")
    else:
        print("Use Threads")
else:
    print("Multi Processing")

Multithreading (Thread-based concurrency)



import threading
import time

def worker(n):
    print(f"Thread {n} starting")
    time.sleep(2)
    print(f"Thread {n} done")

threads = []
for i in range(3):
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

Multiprocessing (Process-based parallelism)



import multiprocessing
import time

def worker(n):
    print(f"Process {n} starting")
    time.sleep(2)
    print(f"Process {n} done")

processes = []
for i in range(3):
    p = multiprocessing.Process(target=worker, args=(i,))
    processes.append(p)
    p.start()

for p in processes:
    p.join()

Asyncio (Asynchronous programming)



import asyncio

async def worker(n):
    print(f"Task {n} starting")
    await asyncio.sleep(2)
    print(f"Task {n} done")

async def main():
    tasks = [worker(i) for i in range(3)]
    await asyncio.gather(*tasks)

asyncio.run(main())