forked from PacktPublishing/AdvancedPythonProgramming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample2.py
More file actions
54 lines (41 loc) · 1.23 KB
/
example2.py
File metadata and controls
54 lines (41 loc) · 1.23 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
# ch13/example2.py
import threading
def writer():
global text
global wcount
while True:
with wcounter:
wcount += 1
if wcount == 1:
read_try.acquire()
with resource:
print(f'Writing being done by {threading.current_thread().name}.')
text += f'Writing was done by {threading.current_thread().name}. '
with wcounter:
wcount -= 1
if wcount == 0:
read_try.release()
def reader():
global rcount
while True:
with read_try:
with rcounter:
rcount += 1
if rcount == 1:
resource.acquire()
print(f'Reading being done by {threading.current_thread().name}:')
print(text)
with rcounter:
rcount -= 1
if rcount == 0:
resource.release()
text = 'This is some text. '
wcount = 0
rcount = 0
wcounter = threading.Lock()
rcounter = threading.Lock()
resource = threading.Lock()
read_try = threading.Lock()
threads = [threading.Thread(target=reader) for i in range(3)] + [threading.Thread(target=writer) for i in range(2)]
for thread in threads:
thread.start()