【问题标题】:Does Python have a similar control mechanism to Java's CountDownLatch?Python 是否有类似于 Java 的 CountDownLatch 的控制机制?
【发布时间】:2012-04-19 21:19:53
【问题描述】:

所以,我首先要说这是一个家庭作业问题。我的教授给了我们一个作业,必须用 Java 写一次,然后用另一种语言写一次;我选择第二种语言是 Python,因为我至少对它有点熟悉。该程序必须按以下方式运行:

start the main method/thread, which we will call parent
start thread child 1 from the parent
start thread grandchild from thread child 1
start thread child 2 from the parent
print grandchild from the grandchild thread
print child 2 from the child 2 thread
print child 1 from the child 1 thread
print parent from the main method/parent thread

这些事情必须按此顺序完成。我使用 CountDownLatch 在 Java 中编写了执行此操作的代码,以便组织这些事情发生的方式。但是,我没有在 Python 中看到类似的机制(尽管我对 Python 的熟悉程度不如 Java)。有没有类似的机制,我可能只是找不到,因为我不知道它叫什么?

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    您可以像这样使用 threading.Condition 实现 CountDownLatch:

    import threading
    
    class CountDownLatch(object):
        def __init__(self, count=1):
            self.count = count
            self.lock = threading.Condition()
    
        def count_down(self):
            self.lock.acquire()
            self.count -= 1
            if self.count <= 0:
                self.lock.notifyAll()
            self.lock.release()
    
        def await(self):
            self.lock.acquire()
            while self.count > 0:
                self.lock.wait()
            self.lock.release()
    

    【讨论】:

      【解决方案2】:

      查看threading 模块中的SemaphoreCondition 类。

      【讨论】:

        【解决方案3】:

        Python 3.2 添加了一个Barrier 类,它与CountDownLatch 有一些重叠的功能。主要区别在于它可以重置,并且没有等待的倒计时方式。

        https://docs.python.org/3/library/threading.html#barrier-objects

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-05-28
          • 2010-10-21
          • 1970-01-01
          • 2020-03-15
          • 1970-01-01
          • 2015-05-20
          • 2011-02-27
          相关资源
          最近更新 更多