-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path_07_locks_python-threads.py
More file actions
63 lines (34 loc) · 1.15 KB
/
_07_locks_python-threads.py
File metadata and controls
63 lines (34 loc) · 1.15 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
'''
Program to demonstrate the locks in python threading
using
lock.acquire()
lock.release()
(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 ')
lock.acquire() #acquire the lock,other threads are not allowed to access the threadduring lock
for _ in range(10):
var_list.append('A')
time.sleep(0.10)
lock.release()
def update_list_B(var_list): #function to write B's to the List
print('update_list_B thread called ')
lock.acquire()
for _ in range(10):
var_list.append('B')
time.sleep(0.10)
lock.release()
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')