forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample3.py
More file actions
48 lines (33 loc) · 1.21 KB
/
example3.py
File metadata and controls
48 lines (33 loc) · 1.21 KB
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
46
47
48
# ch14/example3.py
import threading
import random; random.seed(0)
import time
def update(pause_period):
global counter
with count_lock:
current_counter = counter # reading in shared resource
time.sleep(pause_period) # simulating heavy calculations
counter = current_counter + 1 # updating shared resource
pause_periods = [random.randint(0, 1) for i in range(20)]
###########################################################################
counter = 0
count_lock = threading.Lock()
start = time.perf_counter()
for i in range(20):
update(pause_periods[i])
print('--Sequential version--')
print(f'Final counter: {counter}.')
print(f'Took {time.perf_counter() - start : .2f} seconds.')
###########################################################################
counter = 0
threads = [threading.Thread(target=update, args=(pause_periods[i],)) for i in range(20)]
start = time.perf_counter()
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print('--Concurrent version--')
print(f'Final counter: {counter}.')
print(f'Took {time.perf_counter() - start : .2f} seconds.')
###########################################################################
print('Finished.')