✔️ 10 Python Async & Concurrency Tricks You Should Know! ⚡🐍
1️⃣ اجرای تابع async
import asyncio
async def main():
print("Hello Async")
asyncio.run(main())
2️⃣ اجرای همزمان چند Task
async def task(n):
await asyncio.sleep(1)
return n
results = await asyncio.gather(task(1), task(2))
3️⃣ ایجاد Task در پسزمینه
task = asyncio.create_task(task(3))
4️⃣ محدود کردن همزمانی با Semaphore
sem = asyncio.Semaphore(3)
async with sem:
await some_io()
5️⃣ Timeout برای جلوگیری از Hang
await asyncio.wait_for(task(1), timeout=2)
6️⃣ اجرای کد Blocking داخل Async
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(None, blocking_func)
7️⃣ استفاده از ThreadPoolExecutor
from concurrent.futures import ThreadPoolExecutor
8️⃣ استفاده از ProcessPool برای CPU-Bound
from concurrent.futures import ProcessPoolExecutor
9️⃣ مدیریت Race Condition با Lock
lock = asyncio.Lock()
async with lock:
shared_resource += 1
🔟 Async HTTP Requests با aiohttp
import aiohttp
async with aiohttp.ClientSession() as session:
async with session.get("https://api.example.com") as resp:
data = await resp.json()
> ⚠️ نکته: Async برای I/O-Bound فوقالعاده است، اما برای CPU-Bound از multiprocessing استفاده کن.
#AsyncIO #Concurrency #Backend #Performance #PythonTricks
👇 تو پروژههات بیشتر با I/O-Bound سروکار داری یا CPU-Bound؟