-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathrun_with_condition_extended.py
43 lines (38 loc) · 1.17 KB
/
run_with_condition_extended.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
from threading import Thread, Condition
import time
import random
condition = Condition()
queue = []
MAX_NUM = 10
class ProducerThread(Thread):
def run(self):
nums = range(5)
global queue
while True:
condition.acquire()
if len(queue) == MAX_NUM:
print "Queue full, producer is waiting"
condition.wait()
print "Space in queue, consumer notified producer"
num = random.choice(nums)
queue.append(num)
print "produced: ", num
condition.notify()
condition.release()
time.sleep(random.random())
class ConsumerThread(Thread):
def run(self):
global queue
while True:
condition.acquire()
if not queue:
print "nothing in queue, consumer is waiting"
condition.wait()
print "producer added sth and notified the consumer"
num = queue.pop(0)
print "consumed: ", num
condition.notify()
condition.release()
time.sleep(random.random())
ProducerThread().start()
ConsumerThread().start()