Python Concurrency
Python has three concurrency models: threads (I/O-bound, limited by GIL), multiprocessing (CPU-bound), and asyncio (I/O-bound, single-threaded).
Python has three concurrency models: threads (I/O-bound, limited by GIL), multiprocessing (CPU-bound), and asyncio (I/O-bound, single-threaded).
import threading, multiprocessing, asyncio
# Threads — I/O bound
t = threading.Thread(target=fetch_data, args=(url,))
t.start(); t.join()
# Processes — CPU bound
with multiprocessing.Pool() as pool:
results = pool.map(heavy_compute, data_chunks)
# Asyncio — I/O bound, single thread
async def main():
results = await asyncio.gather(fetch(u1), fetch(u2), fetch(u3))
asyncio.run(main())
GIL limits threads to one CPU core — use multiprocessing for CPU work, asyncio for I/O.