forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample1.py
More file actions
52 lines (38 loc) · 1.18 KB
/
example1.py
File metadata and controls
52 lines (38 loc) · 1.18 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
# ch12/example1.py
import threading
import time
def thread_a():
print('Thread A is starting...')
print('Thread A waiting to acquire lock A.')
lock_a.acquire()
print('Thread A has acquired lock A, performing some calculation...')
time.sleep(2)
print('Thread A waiting to acquire lock B.')
lock_b.acquire()
print('Thread A has acquired lock B, performing some calculation...')
time.sleep(2)
print('Thread A releasing both locks.')
lock_a.release()
lock_b.release()
def thread_b():
print('Thread B is starting...')
print('Thread B waiting to acquire lock B.')
lock_b.acquire()
print('Thread B has acquired lock B, performing some calculation...')
time.sleep(5)
print('Thread B waiting to acquire lock A.')
lock_a.acquire()
print('Thread B has acquired lock A, performing some calculation...')
time.sleep(5)
print('Thread B releasing both locks.')
lock_b.release()
lock_a.release()
lock_a = threading.Lock()
lock_b = threading.Lock()
thread1 = threading.Thread(target=thread_a)
thread2 = threading.Thread(target=thread_b)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print('Finished.')