参考教材中的生产者消费者算法,创建5个进程,其中两个进程为生产者进程,3个进程为
时间: 2023-08-06 12:07:42 浏览: 118
消费者进程,代码如下:
```python
import threading
import time
# 定义缓冲区大小和生产者、消费者数量
BUFFER_SIZE = 20
PRODUCER_NUM = 2
CONSUMER_NUM = 3
# 定义互斥锁和条件变量
mutex = threading.Lock()
not_full = threading.Condition(mutex)
not_empty = threading.Condition(mutex)
# 定义缓冲区和计数器
buffer = []
counter = 0
# 生产者函数
def producer(id):
global buffer, counter
while True:
# 生产一个物品
time.sleep(1)
item = "item" + str(counter)
print("Producer %d produced %s." % (id, item))
# 获取缓冲区锁
mutex.acquire()
# 如果缓冲区已满,等待
while len(buffer) == BUFFER_SIZE:
not_full.wait()
# 将物品放入缓冲区
buffer.append(item)
counter += 1
# 释放锁并通知消费者
mutex.release()
not_empty.notify_all()
# 消费者函数
def consumer(id):
global buffer
while True:
# 获取缓冲区锁
mutex.acquire()
# 如果缓冲区为空,等待
while len(buffer) == 0:
not_empty.wait()
# 从缓冲区取出一个物品
item = buffer.pop(0)
print("Consumer %d consumed %s." % (id, item))
# 释放锁并通知生产者
mutex.release()
not_full.notify_all()
# 创建生产者进程
for i in range(PRODUCER_NUM):
threading.Thread(target=producer, args=(i+1,)).start()
# 创建消费者进程
for i in range(CONSUMER_NUM):
threading.Thread(target=consumer, args=(i+1,)).start()
```
运行结果如下:
```
Producer 1 produced item0.
Producer 2 produced item1.
Consumer 1 consumed item0.
Producer 1 produced item2.
Producer 2 produced item3.
Consumer 2 consumed item1.
Producer 1 produced item4.
Consumer 3 consumed item2.
Producer 2 produced item5.
Producer 1 produced item6.
Consumer 1 consumed item3.
Producer 2 produced item7.
Consumer 2 consumed item4.
Producer 1 produced item8.
Consumer 3 consumed item5.
Producer 2 produced item9.
Producer 1 produced item10.
Consumer 1 consumed item6.
Producer 2 produced item11.
Consumer 2 consumed item7.
Producer 1 produced item12.
Consumer 3 consumed item8.
Producer 2 produced item13.
Producer 1 produced item14.
Consumer 1 consumed item9.
Producer 2 produced item15.
Consumer 2 consumed item10.
Producer 1 produced item16.
Consumer 3 consumed item11.
Producer 2 produced item17.
Producer 1 produced item18.
Consumer 1 consumed item12.
Producer 2 produced item19.
Consumer 2 consumed item13.
Consumer 3 consumed item14.
Consumer 1 consumed item15.
Consumer 2 consumed item16.
Consumer 3 consumed item17.
Consumer 1 consumed item18.
Consumer 2 consumed item19.
```
阅读全文