编写一个生产者消费者队列
时间: 2023-09-15 09:16:35 浏览: 44
以下是一个简单的生产者消费者队列的实现,使用 Python 语言编写。
```python
import threading
class Queue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = []
self.lock = threading.Lock()
self.empty = threading.Condition(self.lock)
self.full = threading.Condition(self.lock)
def put(self, item):
with self.full:
while len(self.queue) == self.capacity:
self.full.wait()
self.queue.append(item)
self.empty.notify()
def get(self):
with self.empty:
while not self.queue:
self.empty.wait()
item = self.queue.pop(0)
self.full.notify()
return item
```
这个队列类有一个限制容量,当队列满时,生产者将等待消费者从队列中删除一些项,以便为其添加新项。同样,当队列为空时,消费者将等待生产者向队列中添加新项。
使用示例:
```python
import time
def producer(q, items):
for item in items:
time.sleep(1)
q.put(item)
def consumer(q):
while True:
item = q.get()
print(item)
q = Queue(5)
threads = [
threading.Thread(target=producer, args=(q, ['item1', 'item2', 'item3'])),
threading.Thread(target=consumer, args=(q,))
]
for t in threads:
t.start()
for t in threads:
t.join()
```
在这个例子中,我们创建了一个队列,将其传递给一个生产者线程和一个消费者线程。生产者将向队列中添加三个项目,每个项目之间间隔一秒钟。消费者将从队列中获取这些项目并将其打印。程序将等待两个线程完成。