Python是否具有与Java CountDownLatch类似的控制机制? [英] Does Python have a similar control mechanism to Java's CountDownLatch?
问题描述
因此,我首先要说这是针对家庭作业的.我的教授给了我们一个作业,必须用Java编写一次,并用另一种语言编写一次.我选择第二种语言是Python,因为我至少有点熟悉.该程序必须以以下方式工作:
So, I will start by saying that this is for a homework problem. My professor gave us an assignment which must be written once in Java and once in another language; I chose the second language to be Python since I'm at least a little familiar with it. The program must work in the following way:
启动我们称为父级的主方法/线程.
Start the main method/thread which we will call parent.
从父级开始线程子级1
start thread child 1 from the parent
从线程子代1启动线程孙子代
start thread grandchild from thread child 1
从父级开始线程子级2
start thread child 2 from the parent
从孙子线程中打印孙子
从子2线程中打印子2
print child 2 from the child 2 thread
从子1线程中打印子1
print child 1 from the child 1 thread
从主方法/父线程中打印父级
print parent from the main method/parent thread
这些事情必须按此顺序完成.我已经编写了使用CountDownLatch在Java中执行此操作的代码,以组织这些事情的发生方式.但是,我没有在Python中看到类似的机制(尽管我不像Java那样对Python熟悉).是否有类似的机制也许因为我不知道它叫什么而无法找到?
These things must be done in this order. I have written code that does this in Java using CountDownLatch in order to organize the way these things occur. However, I didn't see a similar mechanism in Python (although I'm less familiar with Python than Java). Is there a similar mechanism that maybe I just can't find because I don't know what it's called?
推荐答案
您可以使用threading.Condition来实现CountDownLatch:
you can implement CountDownLatch using threading.Condition like this:
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()
这篇关于Python是否具有与Java CountDownLatch类似的控制机制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!