如何知道python信号量值

如何知道python信号量值,python,multithreading,semaphore,Python,Multithreading,Semaphore,我在代码中使用threading.semaphore,我想知道是否有办法使用这样的代码 if(sema.acquire()!=True): #do Somthing 我想在循环中使用这段代码,所以我需要知道信号量是被接收还是被释放 或者在我的代码中使用这样的代码 if(sema.get_value!=1): #do something 我读了这份文件,但找不到我的答案 信号量是围绕着这样一个想法设计的,线程只需要抓取一个信号量,然后等待它变为可用信号量,因为无法预测它们的获取顺序

我在代码中使用threading.semaphore,我想知道是否有办法使用这样的代码

if(sema.acquire()!=True):
   #do Somthing
我想在循环中使用这段代码,所以我需要知道信号量是被接收还是被释放 或者在我的代码中使用这样的代码

if(sema.get_value!=1):
  #do something
我读了这份文件,但找不到我的答案

信号量是围绕着这样一个想法设计的,线程只需要抓取一个信号量,然后等待它变为可用信号量,因为无法预测它们的获取顺序

计数器不是名为“信号量”的抽象的一部分。不能保证您对信号量计数器的访问是原子的。如果您可以窥视计数器,而另一个线程在您使用该信号量之前获取该信号量,您应该怎么做

如果不破坏代码,就无法知道值

您可以使用

if(sema.acquire(blocking=False)):
    # Do something with lock taken
    sema.release()
else:
    # Do something in case when lock is taken by other
这种机制有助于避免复杂情况下的死锁,但也可用于其他目的


其他答案都是正确的,但是对于到达此页面的用户,为了真正了解如何获取信号量值,您可以这样做:

>>> from threading import Semaphore
>>> sem = Semaphore(5)
>>> sem._Semaphore__value
5
>>> sem.acquire()
True
>>> sem._Semaphore__value
4
from threading import Semaphore
sem = Semaphore(5)
print(sem._value)

请注意作为变量
名称前缀的
\u信号量
表示这是一个实现细节。不要基于此变量编写生产代码,因为它将来可能会更改。此外,不要尝试手动编辑该值,否则。。任何坏事都有可能发生。

在python3.6中,您可以得到如下结果:

>>> from threading import Semaphore
>>> sem = Semaphore(5)
>>> sem._Semaphore__value
5
>>> sem.acquire()
True
>>> sem._Semaphore__value
4
from threading import Semaphore
sem = Semaphore(5)
print(sem._value)

此值对调试

有用,您可以考虑使用线程。条件()。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()

不要将布尔值与
进行比较=;如果不是sema.acquire(),请改用