Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know python semaphore value

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

like image 647
Rome Avatar asked May 04 '15 14:05

Rome


People also ask

What is the default value of a semaphore instance in Python?

The 'count' parameter of the Semaphore class is the number of Threads allowed to access simultaneously. The default value of this parameter is 1.

How does semaphore work in Python?

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.

What is the difference between semaphore and bounded semaphore in Python?

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.

What is semaphore multiprocessing?

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.


Video Answer


1 Answers

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.

like image 138
enrico.bacis Avatar answered Oct 06 '22 13:10

enrico.bacis