Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save normanlmfung/d098763369a9241d34d731cc6c3e6333 to your computer and use it in GitHub Desktop.
Save normanlmfung/d098763369a9241d34d731cc6c3e6333 to your computer and use it in GitHub Desktop.
python_syntax_three_semaphore
'''
https://superfastpython.com/asyncio-semaphore/
https://superfastpython.com/thread-semaphore/
https://superfastpython.com/multiprocessing-semaphore-in-python/
There're three versions of Semaphore:
from asyncio import Semaphore
from threading import Semaphore
from multiprocessing import Semaphore
Usage:
'''
import asyncio
semaphore = asyncio.Semaphore(100)
await semaphore.acquire()
semaphore.release()
import multiprocessing
semaphore = multiprocessing.Semaphore(100)
semaphore.acquire()
semaphore.release()
# Can I use with-statement?
import asyncio
async def some_coroutine():
async with asyncio.Semaphore(100) as semaphore:
await semaphore.acquire()
# ... do something ...
semaphore.release()
asyncio.run(some_coroutine())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment