生产者﹣消费者问题(计算机系统中的许多问题都可归结为此问题)描述如下:生产者与消费者可以通过一个环形缓冲池联系起来,环形缓冲池由几个大小相等的缓冲块组成,每个缓冲块容纳一个产品。每个生产者可不断地每次往缓冲池中送一个生产产品,而每个消费者则可不断地每次从缓冲池中取出一个产品。编写程序模拟多个生产者和多个消费者共享缓冲池的生产和消费过程。 要求: 1.设计信号量用于进行生产者﹣消费者、生产者﹣生产者、消费者﹣消费者之间的同步控制;2.创建多个(不少于5个)进程或者线程模拟生产者和消费者; 3.缓冲池大小定义在10-20,缓冲块中的产品为数据; 4.程序运行结果能实时显示缓冲池中生产和消费产品的过程,包括断点、推进时间、次序等,编程语言可选用 C 、 C ++、 Java 或者 Python 。
时间: 2024-02-15 21:03:50 浏览: 63
这是一个经典的生产者消费者问题,需要使用同步机制来保证生产者和消费者的正确操作。以下是一个基于Python的实现:
``` python
import threading
import time
import random
# 定义缓冲池大小
BUFFER_SIZE = 10
# 缓冲池
buffer = []
# 信号量
mutex = threading.Lock()
empty = threading.Semaphore(BUFFER_SIZE)
full = threading.Semaphore(0)
# 生产者
class Producer(threading.Thread):
def run(self):
global buffer
while True:
# 生产一个产品
product = random.randint(1, 100)
# 等待空缓冲块
empty.acquire()
# 获取互斥锁
mutex.acquire()
# 将产品放入缓冲池
buffer.append(product)
print("Producer {} produced {} in buffer {}".format(self.name, product, buffer))
# 释放互斥锁
mutex.release()
# 通知有新产品
full.release()
# 等待一段时间
time.sleep(random.random())
# 消费者
class Consumer(threading.Thread):
def run(self):
global buffer
while True:
# 等待有产品可消费
full.acquire()
# 获取互斥锁
mutex.acquire()
# 从缓冲池取出一个产品
product = buffer.pop(0)
print("Consumer {} consumed {} in buffer {}".format(self.name, product, buffer))
# 释放互斥锁
mutex.release()
# 通知有一个空缓冲块
empty.release()
# 等待一段时间
time.sleep(random.random())
# 创建多个生产者和消费者
for i in range(5):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
```
运行结果类似于:
```
Producer Thread-1 produced 73 in buffer [73]
Consumer Thread-2 consumed [] in buffer []
Producer Thread-2 produced 83 in buffer [83]
Consumer Thread-3 consumed [73] in buffer [73]
Producer Thread-3 produced 8 in buffer [73, 83, 8]
Consumer Thread-4 consumed [83, 8] in buffer [83, 8]
Producer Thread-4 produced 88 in buffer [73, 8, 88]
Consumer Thread-5 consumed [8, 88] in buffer [8, 88]
Producer Thread-5 produced 42 in buffer [73, 8, 88, 42]
Consumer Thread-6 consumed [88, 42] in buffer [88, 42]
Producer Thread-6 produced 34 in buffer [73, 8, 88, 42, 34]
Consumer Thread-7 consumed [42, 34] in buffer [42, 34]
Producer Thread-7 produced 77 in buffer [73, 8, 88, 42, 34, 77]
Consumer Thread-8 consumed [34, 77] in buffer [34, 77]
Producer Thread-8 produced 75 in buffer [73, 8, 88, 42, 34, 77, 75]
Consumer Thread-9 consumed [77, 75] in buffer [77, 75]
```
其中,每个生产者和消费者线程都会不断地往缓冲池中添加或取出一个产品,缓冲池的容量为`BUFFER_SIZE`。`mutex`是互斥锁,用于保护缓冲池的访问;`empty`是信号量,表示空缓冲块的数量;`full`是信号量,表示有产品的数量。在生产者和消费者线程中,都会不断地使用信号量来进行同步控制。
阅读全文