-
Notifications
You must be signed in to change notification settings - Fork 0
/
08_mutex.py
64 lines (49 loc) · 1.73 KB
/
08_mutex.py
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
import logging
import threading
import time
from time import sleep
from concurrent.futures import ThreadPoolExecutor
from concurrent.futures import wait
sum = 0
def thread_kernel_add(thread_index, repeat, value):
logging.info("I am thread %s", thread_index)
global sum # modify the scope of the variable
global lock
logging.info("Initial sum in thread %s : %d", thread_index, sum)
lock.acquire()
for i in range(repeat):
tmp = sum
sleep(0)
tmp = tmp + value
sleep(0)
sum = tmp
lock.release()
logging.info("Final sum in thread %s : %d", thread_index, sum)
logging.info("I am thread %s, and I am done", thread_index)
def thread_kernel_sub(thread_index, repeat, value):
logging.info("I am thread %s", thread_index)
global sum # modify the scope of the variable
global lock
logging.info("Initial sum in thread %s : %d", thread_index, sum)
lock.acquire()
for i in range(repeat):
tmp = sum
sleep(0)
tmp = tmp - value
sleep(0)
sum = tmp
lock.release()
logging.info("Final sum in thread %s : %d", thread_index, sum)
logging.info("I am thread %s, and I am done", thread_index)
if __name__ == "__main__":
format = "%(asctime)s: %(message)s"
logging.basicConfig(format=format, level=logging.INFO, datefmt="%H:%M:%S")
lock = threading.Lock()
# launch the threads
adder = threading.Thread(target=thread_kernel_add, args=(1, 1000000, 100) ) # adder threads
adder.start()
subtractor = threading.Thread(target=thread_kernel_sub, args=(2, 1000000, 100) ) # subtractor threads
subtractor.start()
adder.join()
subtractor.join()
print("Sum = "+ str(sum))