编程实现生产者-消费者问题的模拟
时间: 2024-05-15 10:16:23 浏览: 14
以下是一个基于Python的生产者-消费者问题模拟:
```python
import threading
import time
# 全局变量
BUFFER_SIZE = 10 # 缓冲区大小
buffer = [] # 缓冲区列表
# 生产者线程
class ProducerThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
global buffer
while True:
if len(buffer) < BUFFER_SIZE:
item = time.time() # 生产一个时间戳作为产品
buffer.append(item)
print('{}: 生产了产品 {}'.format(self.name, item))
time.sleep(1) # 生产一个产品需要1秒钟
else:
print('{}: 缓冲区已满,等待消费...'.format(self.name))
time.sleep(0.5) # 如果缓冲区已满,等待0.5秒再继续生产
# 消费者线程
class ConsumerThread(threading.Thread):
def __init__(self, name):
threading.Thread.__init__(self)
self.name = name
def run(self):
global buffer
while True:
if len(buffer) > 0:
item = buffer.pop(0)
print('{}: 消费了产品 {}'.format(self.name, item))
time.sleep(2) # 消费一个产品需要2秒钟
else:
print('{}: 缓冲区为空,等待生产...'.format(self.name))
time.sleep(1) # 如果缓冲区为空,等待1秒再继续消费
# 创建生产者和消费者线程
producer_thread = ProducerThread('生产者')
consumer_thread = ConsumerThread('消费者')
# 启动线程
producer_thread.start()
consumer_thread.start()
# 等待线程结束
producer_thread.join()
consumer_thread.join()
```
在这个模拟中,生产者和消费者分别在不同的线程中运行。生产者在缓冲区未满的情况下生产产品,并将产品添加到缓冲区中;消费者在缓冲区非空的情况下消费产品,并将产品从缓冲区中移除。如果缓冲区已满,生产者线程会等待0.5秒之后再继续生产;如果缓冲区为空,消费者线程会等待1秒之后再继续消费。生产者和消费者线程会一直循环运行,直到程序结束。