-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducter-consumer-con.py
44 lines (39 loc) · 1.03 KB
/
producter-consumer-con.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
from threading import Thread, Condition
import time
import random
import copy
queue = []
con = Condition()
class ProducerThread(Thread):
def run(self):
nums = range(5)
global queue
is_empty = False
while True:
num = random.choice(nums)
con.acquire()
is_empty = len(queue) == 0
queue.append(num)
if is_empty:
con.notify()
con.release()
print "Produced", num
time.sleep(random.random())
class ConsumerThread(Thread):
def run(self):
global queue
tmp_queue = []
while True:
con.acquire()
if queue:
tmp_queue = copy.deepcopy(queue)
queue = []
else:
con.wait()
con.release()
for data in tmp_queue:
print "Consumed", data
tmp_queue = []
#time.sleep(random.random())
ProducerThread().start()
ConsumerThread().start()