1️⃣ Concurrency kya hoti hai?
Concurrency ka matlab hai ek hi samay par multiple tasks ko manage karna — jaise ek program ek saath multiple users ko serve kare. Python me concurrency achieve karne ke main tareeke hain:
- Threads (Lightweight parallel tasks)
- Multiprocessing (Real parallelism using multiple CPU cores)
- Asyncio (Single-threaded but non-blocking async tasks)
2️⃣ Threading — Ek hi process ke andar multiple lightweight threads
Threading use karte hain jab aapko I/O bound tasks perform karne hote hain — jaise file read/write, network calls, etc.
import threading
import time
def task(name):
print(f"Task {name} start ho gaya ⏳")
time.sleep(2)
print(f"Task {name} complete ✅")
t1 = threading.Thread(target=task, args=("A",))
t2 = threading.Thread(target=task, args=("B",))
t1.start()
t2.start()
t1.join()
t2.join()
print("Sab threads complete 🎉")
👉 Output me dono threads parallel run karenge (2 seconds total lagne chahiye, 4 nahi).
---3️⃣ Multiprocessing — True Parallelism 💪
Threading me Python’s GIL (Global Interpreter Lock) ki wajah se ek samay me sirf ek thread execute hota hai. Multiprocessing is limitation ko todta hai — multiple processes use karta hai jo alag CPU cores par run hote hain.
from multiprocessing import Process
import os
import time
def work():
print(f"Process {os.getpid()} start hua")
time.sleep(2)
print(f"Process {os.getpid()} khatam hua")
if __name__ == "__main__":
p1 = Process(target=work)
p2 = Process(target=work)
p1.start()
p2.start()
p1.join()
p2.join()
print("Done ✅")
---
4️⃣ Asyncio — Modern Asynchronous Python ⚡
Asyncio ek single-threaded, single-process event loop hota hai jisme aap asynchronous functions likh sakte ho jo non-blocking hote hain.
import asyncio
async def fetch_data(id):
print(f"Fetching data {id}...")
await asyncio.sleep(2)
print(f"Data {id} ready ✅")
async def main():
await asyncio.gather(fetch_data(1), fetch_data(2), fetch_data(3))
asyncio.run(main())
👉 Output: sab 3 tasks parallelly run karenge using async await.
---5️⃣ Threading vs Multiprocessing vs Asyncio
| Feature | Threading | Multiprocessing | Asyncio |
|---|---|---|---|
| Type | Concurrent | Parallel | Asynchronous |
| Best for | I/O Bound Tasks | CPU Bound Tasks | Network / I/O Bound |
| GIL Affected? | Yes | No | Yes (but single-thread) |
| Complexity | Medium | High | Low/Medium |
6️⃣ Real-life Example: Concurrent Web Scraper
Ye ek simple asyncio-based web scraper example hai jo ek saath multiple URLs fetch karta hai.
import asyncio
import aiohttp
urls = [
"https://example.com",
"https://python.org",
"https://aikipadhai.com"
]
async def fetch(session, url):
async with session.get(url) as response:
print(f"{url} => {response.status}")
async def main():
async with aiohttp.ClientSession() as session:
tasks = [fetch(session, url) for url in urls]
await asyncio.gather(*tasks)
asyncio.run(main())
---
💡 Summary
- Threading: Lightweight, great for I/O-bound work.
- Multiprocessing: Heavy-duty, true CPU parallelism.
- Asyncio: Modern async code with simple syntax.
Har method apne use case ke hisaab se best hai — aur aap inhe combine bhi kar sakte ho large-scale apps me ⚙️