i use threading.semaphore in my code and i wonder if there is way i can use code like This
if(sema.acquire()!=True):
#do Somthing
i want to use this piece of code in loop so i need to get if semaphore is taken or it's released or use code like this in my code
if(sema.get_value!=1):
#do something
i read this doc but i can't find my answer https://docs.python.org/3/library/threading.html
The 'count' parameter of the Semaphore class is the number of Threads allowed to access simultaneously. The default value of this parameter is 1.
A semaphore manages an internal counter which is decremented by each acquire() call and incremented by each release() call. The counter can never go below zero; when acquire() finds that it is zero, it blocks, waiting until some other thread calls release() . Semaphores also support the context management protocol.
Bounded Semaphore is a version of Semaphore that raises a ValueError in release() if it increases the internal counter above the initial value. Changed in version 3.10: Removed the loop parameter.
A semaphore is a concurrency primitive that allows a limit on the number of processes (or threads) that can acquire a lock protecting a critical section. It is an extension of a mutual exclusion (mutex) lock that adds a count for the number of processes that can acquire the lock before additional processes will block.
The other answers are correct but for whom reaches this page in order to actually know how to get the semaphore value you can do it like this:
>>> from threading import Semaphore
>>> sem = Semaphore(5)
>>> sem._Semaphore__value
5
>>> sem.acquire()
True
>>> sem._Semaphore__value
4
Be aware that the _Semaphore__
that prefixes the name of the variable value
means that this is an implementation detail. Do not write production code based on this variable as it may change in the future. Moreover do not try to edit the value manually, otherwise.. any bad thing can happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With