【问题标题】:Implementing synchronization barriers实现同步屏障
【发布时间】:2015-03-09 17:08:31
【问题描述】:

在这个网站http://www.cs.cornell.edu/courses/cs4410/2010fa/synchreview.pdf 上,它说为多次迭代实现屏障必须通过以下方式实现:

class Barrier:
    def __init__(self, N):
        self.incount = 0
        self.outcount = 0
        self.N = N
        self.lock = Lock()
        self.everyoneatbarrier = Condition(self.lock)

    def barrier(self, processid):
        with self.lock:
            self.incount += 1
            if self.incount == self.N
                self.everoneatbarrier.notifyAll()
            while self.incount < self.N or 
                (self.incount >= self.N and self.outcount < self.N):
                self.everyoneatbarrier.wait()
            self.outcount += 1
            if self.outcount == self.N:
                self.outcount = 0
                self.incount ­= self.N

如果我们只使用一个简单的 if-else 语句会不会更简单:

    def barrier(self, processid):
        with self.lock:
            self.count += 1
            if self.count == self.N :
                self.everyoneatbarrier.notifyAll()
            else :
                self.everyoneatbarrier.wait()
            self.count = 0

我不明白所有额外的努力。谢谢大家。

【问题讨论】:

    标签: multithreading synchronization deadlock barrier


    【解决方案1】:

    示例中的额外工作是由于保持与循环屏障行为相关的状态(它可以在所有等待线程都被释放后重用)。

    在您的简化中,我认为有两个问题,它不可重用,并且您没有保护等待调用免受虚假唤醒:

      def barrier(self, processid):
        with self.lock:
            self.count += 1
            if self.count == self.N :
                self.everyoneatbarrier.notifyAll()
            else :
                while self.count < N:
                    self.everyoneatbarrier.wait()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-02
      • 1970-01-01
      • 2015-01-04
      • 1970-01-01
      • 2021-12-02
      • 1970-01-01
      • 2013-04-25
      • 2016-06-22
      相关资源
      最近更新 更多