4

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

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

谢谢!

4

2 回答 2

3

我很确定 multiprocessing 包的内置同步原语提供您需要的东西:https ://docs.python.org/2/library/multiprocessing.html#synchronization-primitives

于 2015-02-06T22:12:57.313 回答
1

这是多处理的类比,至于来自这里的线程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()
于 2019-05-03T18:55:43.180 回答