Rome
Rome

Reputation: 603

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

Upvotes: 9

Views: 19041

Answers (5)

driedler
driedler

Reputation: 4190

You might consider using a threading.Condition() instead. e.g:

import threading

class ConditionalSemaphore(object):
    def __init__(self, max_count):
        self._count = 0
        self._max_count = max_count
        self._lock = threading.Condition()

    @property
    def count(self):
        with self._lock:
            return self._count

    def acquire(self):
        with self._lock:
            while self._count >= self._max_count:
                self._lock.wait()
            self._count += 1

    def release(self):
        with self._lock:
            self._count -= 1
            self._lock.notify()

Upvotes: 1

hantian_pang
hantian_pang

Reputation: 1039

In python3.6, you can get is like this:

from threading import Semaphore
sem = Semaphore(5)
print(sem._value)

This value is useful for debug

Upvotes: 13

Tsyvarev
Tsyvarev

Reputation: 65928

You can use

if(sema.acquire(blocking=False)):
    # Do something with lock taken
    sema.release()
else:
    # Do something in case when lock is taken by other

Such mechanism is useful for avoiding deadlocks in complex cases, but also may be used for other purposes.

More information on acquire function

Upvotes: 8

enrico.bacis
enrico.bacis

Reputation: 31494

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.

Upvotes: 15

knitti
knitti

Reputation: 7033

Semaphores are designed around the idea, that threads just grab one, and wait until it becomes available, because it's not really predictable in which order they wil be acquired.

The counter is not part of the abstraction called 'Semaphore'. It is not guaranteed, that your access to the semaphore counter is atomic. If you could peek into the counter, and another thread acquires the semaphore before you do anything with it, what should you do?

Without breaking your code you can't know the value.

Upvotes: 10

Related Questions