-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path08Locks.py
More file actions
35 lines (27 loc) · 793 Bytes
/
Copy path08Locks.py
File metadata and controls
35 lines (27 loc) · 793 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
import threading
import time
sharedCount = 10
lock = threading.Lock()
def increment(toAdd):
with lock:
global sharedCount
localCounter = sharedCount
localCounter += toAdd
time.sleep(1)
sharedCount = localCounter
print(f'{threading.current_thread().name} inc x {toAdd}, x: {sharedCount}')
lock.acquire()
# Critical section
localCounter = sharedCount
localCounter += toAdd
time.sleep(1)
sharedCount = localCounter
print(f'{threading.current_thread().name} inc x {toAdd}, x: {sharedCount}')
lock.release()
t1 = threading.Thread(target=increment, args=(5,))
t2 = threading.Thread(target=increment, args=(10,))
t1.start()
t2.start()
t1.join()
t2.join()
print(f'The final value of x is {sharedCount}')