创建多个(不少于5个)进程或者线程模拟生产者和消费者
时间: 2024-01-14 17:05:06 浏览: 25
好的,以下是一个使用 Python 多线程模拟生产者和消费者的示例代码,其中创建了5个生产者和5个消费者线程,它们共享一个缓冲区:
```python
import threading
import time
import random
BUFFER_SIZE = 10 # 缓冲区大小
buffer = [0] * BUFFER_SIZE # 缓冲区
in_index = 0 # 生产者放置物品的位置
out_index = 0 # 消费者获取物品的位置
count = 0 # 缓冲区中物品的数量
lock = threading.Lock() # 线程锁
# 生产者线程
class ProducerThread(threading.Thread):
def run(self):
global in_index, count
while True:
time.sleep(random.random()) # 生产物品需要一定的时间
item = random.randint(0, 100) # 生产一个随机物品
lock.acquire() # 获取线程锁
if count < BUFFER_SIZE:
buffer[in_index] = item
in_index = (in_index + 1) % BUFFER_SIZE
count += 1
print(f"生产者 {self.name} 生产了物品 {item},缓冲区中物品数量为 {count}")
else:
print(f"生产者 {self.name} 尝试生产物品 {item},但缓冲区已满,等待消费者消费")
lock.release() # 释放线程锁
# 消费者线程
class ConsumerThread(threading.Thread):
def run(self):
global out_index, count
while True:
time.sleep(random.random()) # 消费物品需要一定的时间
lock.acquire() # 获取线程锁
if count > 0:
item = buffer[out_index]
out_index = (out_index + 1) % BUFFER_SIZE
count -= 1
print(f"消费者 {self.name} 消费了物品 {item},缓冲区中物品数量为 {count}")
else:
print(f"消费者 {self.name} 尝试消费物品,但缓冲区已空,等待生产者生产")
lock.release() # 释放线程锁
# 创建生产者线程和消费者线程
producers = [ProducerThread(name=f"P{i}") for i in range(5)]
consumers = [ConsumerThread(name=f"C{i}") for i in range(5)]
# 启动线程
for p in producers:
p.start()
for c in consumers:
c.start()
# 等待线程结束
for p in producers:
p.join()
for c in consumers:
c.join()
```
上述代码中,每个生产者线程随机生成一个物品,并将其放入缓冲区;每个消费者线程从缓冲区中取出一个物品进行消费。当缓冲区已满时,生产者线程需要等待;当缓冲区已空时,消费者线程需要等待。使用线程锁来保证生产者和消费者之间的同步,避免竞争条件和死锁等问题的发生。