Middle
How does Semaphore differ from Lock in asyncio?
sobes.tech AI
Answer from AI
In asyncio, Lock and Semaphore are used to control access to resources, but they differ in purpose and behavior.
-
Lockis a simple locking mechanism that allows only one coroutine to access the resource at a time. If theLockis occupied, other coroutines wait for it to be released. -
Semaphoreallows limiting the number of coroutines that can access the resource simultaneously, with the limit set at creation. For example,Semaphore(3)allows three coroutines to work at the same time.
Example usage:
import asyncio
async def worker(sem, worker_id):
async with sem:
print(f"Worker {worker_id} started")
await asyncio.sleep(1)
print(f"Worker {worker_id} finished")
async def main():
sem = asyncio.Semaphore(2) # maximum 2 coroutines at the same time
await asyncio.gather(*(worker(sem, i) for i in range(5)))
asyncio.run(main())
In this example, no more than two workers will run simultaneously.
Thus, Lock is a special case of a semaphore with a maximum value of 1.