-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathexer02b04_producer_consumer.py
55 lines (40 loc) · 1.05 KB
/
exer02b04_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
55
'''
THE PRODUCER-CONSUMER PROBLEM
SOLUTION TYPE B: USING SEMAPHORES
Version B04: Multiple fast producers, multiple slow consumers
'''
import time
import threading
def producer(
sem_fill: threading.Semaphore,
sem_empty: threading.Semaphore,
q: list,
start_value: int
):
time.sleep(1)
i = 1
while True:
sem_empty.acquire()
q.append(i + start_value)
sem_fill.release()
i += 1
def consumer(
sem_fill: threading.Semaphore,
sem_empty: threading.Semaphore,
q: list
):
while True:
sem_fill.acquire()
data = q.pop(0)
print('Consumer', data)
time.sleep(1)
sem_empty.release()
s_fill = threading.Semaphore(0) # item produced
s_empty = threading.Semaphore(1) # remaining space in queue
que = []
NUM_PRODUCERS = 3
NUM_CONSUMERS = 2
for i in range(NUM_PRODUCERS):
threading.Thread(target=producer, args=(s_fill, s_empty, que, i * 1000)).start()
for _ in range(NUM_CONSUMERS):
threading.Thread(target=consumer, args=(s_fill, s_empty, que)).start()