ReverseSemaphore无法在python中工作

时间:2015-01-06 04:31:46

标签: python multiprocessing semaphore

我想编写自己的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

1 个答案:

答案 0 :(得分:1)

由于在不同的帖子中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对象都有自己的属性。这就是为什么在流程1中,current的值不会增加到2。

这是关于Python中线程之间通信的一个很好的指导。我相信你可以在里面找到答案。

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

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