-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_08_locks_context_manager_python-threads.py
More file actions
65 lines (35 loc) · 1.28 KB
/
_08_locks_context_manager_python-threads.py
File metadata and controls
65 lines (35 loc) · 1.28 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
'''
Program to demonstrate the locks in python threading
using context manager
with lock:
(c) www.xanthium.in
https://www.xanthium.in/creating-threads-sharing-synchronizing-data-using-queue-lock-semaphore-python
'''
import time
import threading
def update_list_A(var_list): #function to write A's to the List
print('update_list_A thread called ')
#acquire the lock,other threads are not allowed to access the thread during lock
with lock:
for _ in range(10):
var_list.append('A')
time.sleep(0.10)
#lock is released automatically
def update_list_B(var_list): #function to write B's to the List
print('update_list_B thread called ')
#acquire the lock,other threads are not allowed to access the thread during lock
with lock:
for _ in range(10):
var_list.append('B')
time.sleep(0.10)
#lock is released automatically
lock = threading.Lock()
shared_list =[] #Shared variable to be modified in threads
t1 = threading.Thread(target = update_list_A, args = (shared_list,))
t2 = threading.Thread(target = update_list_B, args = (shared_list,))
t1.start()
t2.start()
t1.join()
t2.join()
print(f'\n{shared_list}')
print('\nEnd of Main Thread\n')