-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3_shared_data_without_lock.py
More file actions
87 lines (62 loc) · 2.65 KB
/
3_shared_data_without_lock.py
File metadata and controls
87 lines (62 loc) · 2.65 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
"""
Topic: Shared Data, Lock
Description: See what happens if we do not use mutual exclusion for shared data when we use multithread
"""
from concurrent.futures import ThreadPoolExecutor
import time
import logging
class SharedDataWithoutLock:
# Shared Data => self.value
def __init__(self) -> None:
self.value = 0
def increase_value(self, name):
"""
Pretend how assembly code works when we change the value
1. Get the value
2. Update the value
3. Save the value
However, what if two or more threads get the value before save its value?
Ex) Show One of the possible case when if increase the value 3 times
value T1 T2 T3
0 Get v: 0
Update v: 1
Context Swtiching ->
Get v: 0
Update v: 1
1 Save the value
Done
Context Switching ->
Get v: 1
Update v: 2
2 Save the value
Done
<- Context Switching
1 Save the value
Done
"""
logging.info("Thread %s started", name)
get_value = self.value
logging.info("Thread %s starts getting the value -> %d",
name, get_value)
get_value += 1
logging.info("Thread %s starts updating the value -> %d",
name, get_value)
# pretend context switching
time.sleep(0.01)
self.value = get_value
logging.info("Thread %s starts saving the value -> %d",
name, self.value)
def main():
log_format = "%(asctime)s: %(message)s"
logging.basicConfig(format=log_format,
level=logging.INFO, datefmt="%H:%M:%S")
logging.info("Main-Thread starts")
logging.info("Creates Thread Pool")
sharedData = SharedDataWithoutLock()
with ThreadPoolExecutor(max_workers=3) as executor:
for name in ["First", "Second", "Third"]:
executor.submit(sharedData.increase_value, name)
print("Final Value => ", sharedData.value)
logging.info("Main-Thread done")
if __name__ == "__main__":
main()