【问题标题】:how to know python semaphore value如何知道python信号量值
【发布时间】:2015-07-13 23:20:38
【问题描述】:

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

if(sema.acquire()!=True):
   #do Somthing

我想在循环中使用这段代码,所以我需要获取信号量是被占用还是被释放 或者在我的代码中使用这样的代码

if(sema.get_value!=1):
  #do something

我阅读了这个文档,但我找不到我的答案 https://docs.python.org/3/library/threading.html

【问题讨论】:

  • 不要将布尔值与!= 进行比较;请改用if not sema.acquire()

标签: python multithreading semaphore


【解决方案1】:

其他答案是正确的,但为了真正知道如何获取信号量值,您可以这样做:

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

请注意,变量 value 名称前面的 _Semaphore__ 表示这是一个实现细节。不要基于此变量编写生产代码,因为它将来可能会更改。此外,不要尝试手动编辑该值,否则..可能会发生任何不好的事情。

【讨论】:

    【解决方案2】:

    在python3.6中,可以得到是这样的:

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

    这个值对调试很有用

    【讨论】:

      【解决方案3】:

      信号量是围绕这样的想法设计的,即线程只抓取一个,然后等待它可用,因为无法真正预测它们将被获取的顺序。

      计数器不是称为“信号量”的抽象的一部分。不能保证您对信号量计数器的访问是原子的。如果您可以窥视计数器,而另一个线程在您对其进行任何操作之前获取了信号量,您应该怎么做?

      如果不破坏代码,您将无法知道其价值。

      【讨论】:

        【解决方案4】:

        你可以使用

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

        这种机制对于避免复杂情况下的死锁很有用,但也可以用于其他目的。

        More information on acquire function

        【讨论】:

          【解决方案5】:

          您可以考虑改用 threading.Condition()。例如:

          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()
          

          【讨论】:

            猜你喜欢
            • 2018-04-02
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多