生产者消费者问题的具体代码
时间: 2024-04-14 07:10:19 浏览: 16
以下是一个典型的生产者消费者问题的代码实现,使用了Python的多线程模块:
```python
import threading
import time
import random
# 生产者类
class Producer(threading.Thread):
def __init__(self, threadID, name, counter, queue):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.queue = queue
def run(self):
while True:
# 模拟生产过程
time.sleep(random.randint(1, 5))
item = random.randint(1, 10)
print("Producer %d produced item %d" % (self.threadID, item))
# 将生产的物品放入队列
self.queue.put(item)
# 消费者类
class Consumer(threading.Thread):
def __init__(self, threadID, name, counter, queue):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.queue = queue
def run(self):
while True:
# 从队列中取出物品
item = self.queue.get()
# 模拟消费过程
time.sleep(random.randint(1, 5))
print("Consumer %d consumed item %d" % (self.threadID, item))
# 标记物品已被处理
self.queue.task_done()
# 主程序
if __name__ == "__main__":
# 创建一个队列
queue = queue.Queue()
# 创建5个生产者线程
for i in range(5):
t = Producer(i+1, "Producer%d" % (i+1), i+1, queue)
t.start()
# 创建3个消费者线程
for i in range(3):
t = Consumer(i+1, "Consumer%d" % (i+1), i+1, queue)
t.start()
# 等待队列中的所有物品被处理完
queue.join()
```
在这个代码中,生产者和消费者都是继承自Python的`threading.Thread`类,通过重写`run()`方法实现了线程的逻辑。
生产者和消费者共用了一个队列,生产者将生产的物品放入队列,消费者从队列中取出物品进行处理。为了保证并发安全,使用了Python的`queue`模块提供的线程安全队列。
在主程序中,创建了5个生产者线程和3个消费者线程,并将它们启动。最后等待队列中的所有物品被处理完,使用了`queue.join()`方法。这个方法会阻塞当前线程,直到队列中的所有物品被处理完毕。