apache-ignite
90 строк · 2.5 Кб
1# Licensed to the Apache Software Foundation (ASF) under one or more
2# contributor license agreements. See the NOTICE file distributed with
3# this work for additional information regarding copyright ownership.
4# The ASF licenses this file to You under the Apache License, Version 2.0
5# (the "License"); you may not use this file except in compliance with
6# the License. You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16"""
17This module contains concurrent utils.
18"""
19
20import threading
21
22
23class CountDownLatch:
24"""
25A count-down latch.
26"""
27def __init__(self, count=1):
28self.count = count
29self.cond_var = threading.Condition()
30
31def count_down(self):
32"""
33Decreases the latch counter.
34"""
35with self.cond_var:
36if self.count > 0:
37self.count -= 1
38if self.count == 0:
39self.cond_var.notifyAll()
40
41def wait(self):
42"""
43Blocks current thread if the latch is not free.
44"""
45with self.cond_var:
46while self.count > 0:
47self.cond_var.wait()
48
49
50class AtomicValue:
51"""
52An atomic reference holder.
53"""
54def __init__(self, value=None):
55self.value = value
56self.lock = threading.Lock()
57
58def set(self, value):
59"""
60Sets new value to hold.
61:param value: New value to hold.
62"""
63with self.lock:
64self.value = value
65
66def get(self):
67"""
68Gives current value.
69"""
70with self.lock:
71return self.value
72
73def compare_and_set(self, expected, value):
74"""
75Sets new value to hold if current one equals expected.
76:param expected: The value to compare with.
77:param value: New value to hold.
78"""
79return self.check_and_set(lambda: self.value == expected, value)
80
81def check_and_set(self, condition, value):
82"""
83Sets new value to hold by condition.
84:param condition: The condition to check.
85:param value: New value to hold.
86"""
87with self.lock:
88if condition():
89self.value = value
90return self.value
91