-
Notifications
You must be signed in to change notification settings - Fork 0
/
thread_test_03.py
100 lines (51 loc) · 1.2 KB
/
thread_test_03.py
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import threading
import time
class Producer(threading.Thread):
def __init__(self, t_name):
threading.Thread.__init__(self, name=t_name)
def run(self):
global x
return 0
def sell(self):
global x
con.acquire()
if x > 0:
con.wait()
else:
for i in range(5):
x=x+1
print ("producing..." + str(x))
con.notify()
print (x)
con.release()
class Consumer(threading.Thread):
def __init__(self, t_name):
threading.Thread.__init__(self, name=t_name)
def run(self):
return 0
def buy(self):
global x
con.acquire()
if x == 0:
print ('consumer wait1')
con.wait()
else:
for i in range(5):
x=x-1
print ("consuming..." + str(x))
con.notify()
print (x)
con.release()
con = threading.Condition()
x=0
print ('start consumer')
c=Consumer('consumer')
print ('start producer')
p=Producer('producer')
p.start()
c.start()
while True:
p.sell()
c.buy()
time.sleep(1)
print (x)