-
Notifications
You must be signed in to change notification settings - Fork 1
/
producer_consumer.py
54 lines (41 loc) · 1.21 KB
/
producer_consumer.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
import time
import random
import threading
queue = []
MAX_NUM = 2
condition = threading.Condition()
class Produce(threading.Thread):
def run(self):
tid = threading.get_ident()
num = 1
global queue
while True:
condition.acquire()
while len(queue) == MAX_NUM:
print("Queue is full", tid, "is waiting....")
condition.wait()
print(tid, "wake up")
if len(queue) == 0:
condition.notify()
queue.append(num)
print("Produced", num)
condition.release()
num += 1
time.sleep(random.random())
class Consume(threading.Thread):
def run(self):
global queue
tid = threading.get_ident()
while True:
condition.acquire()
while len(queue) == 0:
print("queue is empty", tid, "is waiting...")
condition.wait()
print(tid, "wake up")
if len(queue) == MAX_NUM:
condition.notify()
print("consumed", queue.pop(0))
condition.release()
time.sleep(random.random())
Produce().start()
Consume().start()