ReverseSemaphore 在 python 中不工作

ReverseSemaphore not working in python

我想编写自己的 ReverseSemaphore,但不知何故它不起作用!

from time import sleep
import multiprocessing

class ReverseSemaphore(object):

    def __init__(self, countTo):
        current = 0
        self.countTo = int(countTo)
        self._cur = None
        self.event = multiprocessing.Event()
        self.clear()
        self.lock = multiprocessing.RLock()

    def _dec(self):
        self.lock.acquire()
        self.current -= 1
        print("decreased to %s" % self.current)
        self.lock.release()

    def _inc(self):
        print("acq")
        self.lock.acquire()
        self.current += 1
        print("increased to %s" % self.current)
        self.lock.release()
        print("released")

    def clear(self):
        self.lock.acquire()
        self.event.clear()
        self.lock.release()

    def wait(self):
        self._inc()
        if self.current < self.countTo:
            print("current=%s, countTo=%s, waiting" % (self.current, self.countTo))
            self.clear()
            self.event.wait()
        else:
            self.event.set()

    def ready(self):
        self._dec()

def action(num, reverseSemaphore):
    print ("process %d started" % num)
    reverseSemaphore.wait()
    #do some working code but simulate with sleep for the example
    sleep(3)

if __name__ == "__main__":
    count = 2
    reverseSemaphore = ReverseSemaphore(count)
    for i in range(count):
        p = multiprocessing.Process(target=action, args=(i, reverseSemaphore))
        p.start()

会给我这个输出:

thread 0 started
acq
increased to 1
released
current=1, countTo=2, waiting
thread 1 started
acq
increased to 1
released
current=1, countTo=2, waiting

然后我遇到了死锁....这里的问题是,我希望进程 1 将计数器增加到 2,这应该释放两者.... 为什么我的 ReverseSemaphore.current 增加到 1 而不是 2

因为在不同的线程中,reverseSemaphore是不同的,你可以从id()结果中看出。像这样:

...
def action(num, reverseSemaphore):
    print ("process %d started" % num)
    print ("id of reverseSemaphore in this thread is: %d" % id(reverseSemaphore))
    reverseSemaphore.wait()
    #do some working code but simulate with sleep for the example
    sleep(3)
...

输出:

process 1 started
id of reverseSemaphore in this thread is: 43735080
acq
increased to 1
released
current=1, countTo=2, waiting
process 0 started
id of reverseSemaphore in this thread is: 44521400
acq
increased to 1
released
current=1, countTo=2, waiting

如您所见,线程中的每个 reverseSemaphore 对象都有自己的属性 current。这就是为什么在进程 1 中,current 的值不会增加到 2.

这里有一个关于 Python 中线程间通信的很好的说明。相信你一定能从中找到答案。

http://pymotw.com/2/multiprocessing/communication.html

希望我的回答对您有所帮助。 :)