forked from dabeaz/python-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample1.py
More file actions
45 lines (39 loc) · 1023 Bytes
/
Copy pathexample1.py
File metadata and controls
45 lines (39 loc) · 1023 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import threading
class SharedCounter:
'''
A counter object that can be shared by multiple threads.
'''
def __init__(self, initial_value = 0):
self._value = initial_value
self._value_lock = threading.Lock()
def incr(self,delta=1):
'''
Increment the counter with locking
'''
with self._value_lock:
self._value += delta
def decr(self,delta=1):
'''
Decrement the counter with locking
'''
with self._value_lock:
self._value -= delta
def test(c):
for n in range(1000000):
c.incr()
for n in range(1000000):
c.decr()
if __name__ == '__main__':
c = SharedCounter()
t1 = threading.Thread(target=test, args=(c,))
t2 = threading.Thread(target=test, args=(c,))
t3 = threading.Thread(target=test, args=(c,))
t1.start()
t2.start()
t3.start()
print('Running test')
t1.join()
t2.join()
t3.join()
assert c._value == 0
print('Looks good!')