【问题标题】:Python 2.7 Multiprocessing BarrierPython 2.7 多处理屏障
【发布时间】:2015-04-07 04:16:42
【问题描述】:
【问题讨论】:
标签:
python
python-2.7
multiprocessing
barrier
【解决方案1】:
【讨论】:
-
好的,谢谢。我在这个线程中找到了这段代码:stackoverflow.com/questions/26622745/…,我希望将它与来自多处理模块的信号量一起使用应该可以正常工作。类屏障: def __init__(self, n): self.n = n self.count = 0 self.mutex = Semaphore(1) self.barrier = Semaphore(0) def wait(self): self.mutex.acquire() self.count = self.count + 1 self.mutex.release() if self.count == self.n: self.barrier.release() self.barrier.acquire() self.barrier.release()
【解决方案2】:
这是多处理的类比,至于线程从这里http://stackoverflow.com/questions/26622745/implementing-barrier-in-python2-7:
from multiprocessing import Process, Semaphore, Value
class Barrier:
def __init__(self, n):
self.n = n
self.count = Value('i', 0)
self.mutex = Semaphore(1)
self.barrier = Semaphore(0)
def wait(self):
self.mutex.acquire()
self.count.value += 1
self.mutex.release()
if self.count.value == self.n:
self.barrier.release()
self.barrier.acquire()
self.barrier.release()
然后是主线程中的使用示例:
barrier = Barrier(2)
process = Process(target = my_second_thread, args = (barrier,))
process.start()