🐍 Python Tutorial: Concurrency & Async Programming
- Threading – lightweight, shared-memory tasks
- Multiprocessing – separate processes, ideal for CPU-bound work
- AsyncIO – cooperative multitasking for I/O-bound tasks
1. Threading
Threads share memory and are great for I/O-bound operations (like file reading or network calls).
import threading
def greet():
print("Hello from thread!")
thread = threading.Thread(target=greet)
thread.start()
thread.join()2. Multiprocessing
Use this for CPU-bound tasks. It bypasses Python's GIL (Global Interpreter Lock) by creating new processes.
from multiprocessing import Process
def compute():
print("Heavy computation in a separate process.")
process = Process(target=compute)
process.start()
process.join()3. AsyncIO
AsyncIO uses cooperative multitasking and is excellent for managing many concurrent I/O tasks.
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(say_hello())4. When to Use Each
- Threading: Ideal for I/O-bound tasks like downloading, file access
- Multiprocessing: Use for CPU-heavy tasks like data processing or math
- AsyncIO: Best when handling thousands of network or file operations concurrently
5. Async Example with HTTP
Here's an example of asynchronous HTTP requests using aiohttp:
import asyncio
import aiohttp
async def fetch(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.text()
async def main():
html = await fetch("https://example.com")
print(html)
asyncio.run(main())