import time
import random
from multiprocessing import Process, Queue
# 生产者
def producer(q, i):
food = 'Spam-%d' % i
time.sleep(random.uniform(2, 5))
timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('时间:%s\t生产者:%d 生产了 %d' % (timeVal, i, i))
q.put(food)
# 消费者
def consumer(q, i):
while True:
food = q.get()
if not food:break
time.sleep(random.uniform(1, 2))
timeVal = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print('时间:%s\t消费者: %d\t吃了 %s' % (timeVal, i, food))
if __name__ == '__main__':
q = Queue()
producerPs = []
for n in range(1, 16):
producerPs.append(Process(target=producer, args=(q, n)))
for producerP in producerPs:
producerP.start()
consumerPs = []
for n in range(1, 6):
consumerPs.append(Process(target=consumer, args=(q, n)))
for consumerP in consumerPs:
consumerP.start()
for producerP in producerPs:
producerP.join()
for consumerP in consumerPs:
q.put(None)
for consumerP in consumerPs:
consumerP.join()
print('end')
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,携手博客园推出1Panel与Halo联合会员
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步