【问题标题】:Python 2.7 Multiprocessing BarrierPython 2.7 多处理屏障
【发布时间】:2015-04-07 04:16:42
【问题描述】:

我使用的是 Python 2.7,并且一直在将多线程代码转换为多处理代码以避免 GIL 锁定问题。但是,我在多处理模块中没有看到障碍实现(有什么想法如何实现吗?)。

我看到了这个问题: Is it possible to use multiprocessing.Event to implement a synchronization barrier for pool of processes? 但我不确定它是否会正常工作,因为它不使用任何锁!

谢谢!

【问题讨论】:

    标签: python python-2.7 multiprocessing barrier


    【解决方案1】:

    我很确定 multiprocessing 包的内置同步原语可以满足您的需求:https://docs.python.org/2/library/multiprocessing.html#synchronization-primitives

    【讨论】:

    • 好的,谢谢。我在这个线程中找到了这段代码: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()
    

    【讨论】:

      猜你喜欢
      • 2011-10-12
      • 2017-04-23
      • 1970-01-01
      • 2016-07-21
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      相关资源
      最近更新 更多