countanddown java,Python是否具有与Java CountDownLatch类似的控制机制?

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.

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

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?

解决方案

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值