blob: 5d3c398644cc44e33661198575a8154e808b8e20 [file] [log] [blame]
Illyoung Choia9d2c2c2019-07-12 13:29:42 -07001#!/usr/bin/env python3
2
3# Copyright 2019-present Open Networking Foundation
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18Count-down latch
19"""
20
21import threading
22import time
23
24
25class CountDownLatch(object):
26 def __init__(self, count=1):
27 self.count = count
28 self.condition = threading.Condition()
29
30 def count_down(self, count=1):
31 self.condition.acquire()
32 self.count -= count
33 if self.count <= 0:
34 self.condition.notifyAll()
35 self.condition.release()
36
37 def wait(self, timeout=0):
38 self.condition.acquire()
39 start_time = time.time()
40
41 while self.count > 0:
42 self.condition.wait(timeout)
43 cur_time = time.time()
44 if cur_time - start_time >= timeout:
45 break
46
47 self.condition.release()
48 if self.count <= 0:
49 return True
50 else:
51 # timeout
52 return False
53
54 def get_count(self):
55 return self.count