编写程序实现基于队列缓存数据的生产者-消费者模型
时间: 2023-12-10 15:06:28 浏览: 39
好的,下面是基于队列缓存数据的生产者-消费者模型的 Python 代码实现:
```python
import threading
import time
import queue
# 创建一个队列缓存数据
queue_buffer = queue.Queue(10)
class ProducerThread(threading.Thread):
def run(self):
global queue_buffer
# 生产者不断地向队列中放入数据
while True:
if queue_buffer.full():
print('队列已满,等待消费...')
else:
item = time.strftime('%H:%M:%S', time.localtime())
queue_buffer.put(item)
print('生产者放入数据:', item)
time.sleep(1)
class ConsumerThread(threading.Thread):
def run(self):
global queue_buffer
# 消费者不断地从队列中取出数据
while True:
if queue_buffer.empty():
print('队列为空,等待生产...')
else:
item = queue_buffer.get()
print('消费者取出数据:', item)
time.sleep(2)
# 创建一个生产者线程和一个消费者线程
producer = ProducerThread()
consumer = ConsumerThread()
# 启动线程
producer.start()
consumer.start()
```
以上代码实现了一个简单的基于队列缓存数据的生产者-消费者模型。生产者线程不断地向队列中放入数据,消费者线程不断地从队列中取出数据,当队列满时生产者线程等待,当队列为空时消费者线程等待。你可以按照这个思路进行修改,以满足自己的需求。