-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducerConsumer.py
53 lines (48 loc) · 1.42 KB
/
producerConsumer.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
from threading import Condition, Thread, Lock
import time
import random
queue = []
qt = 0
lock = Lock()
condition = Condition()
nums = list(range(10))
class Consumer(Thread):
def run(self):
global queue
global nums
while True:
condition.acquire()
global qt
qt = int(random.random()*5)
if len(queue)<qt:
print("not enough prods to consume")
condition.wait()
print("producer notified")
for i in range(qt):
num = queue.pop(0)
nums.append(num)
print("consumed", num)
condition.release()
qt = 0
time.sleep(random.random())
class Producer(Thread):
def run(self):
global nums
global queue
while True:
condition.acquire()
if qt:
for i in range(qt-len(queue)):
num = random.choice(nums)
queue.append(num)
nums.remove(num)
print("produced",num)
condition.notify()
num = random.choice(nums)
queue.append(num)
nums.remove(num)
print("produced",num)
condition.release()
time.sleep(random.random())
Producer().start()
Consumer().start()