原因: 在并发编程中使用生产者和消费者模式能够解决绝大多数并发问题。
# coding=utf-8
import random
import time
import logging
import multiprocessing
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [*] %(message)s"
)
'''
multiprocessing模块支持进程间通信的两种主要形式:管道和队列
都是基于消息传递实现的,但是队列接口
'''
def consumer (q, name):
# 处理数据
while True:
time.sleep(random.uniform(0.5, 1))
food = q.get()
if food is None: # 关卡
break
logging.info(f'\t{name} {food}')
def producer (q, name, food):
# 获取数据
for i in range(1, 11):
q.put("拿了" + food + "的编号:" + str(i))
logging.info(f'{name} 生产{food}的编号:{i}')
time.sleep(random.uniform(0.3, 0.8))
def main (ctx):
q = ctx.Queue()
ctx.Process(target=consumer, args=(q, '迷心兔')).start()
ctx.Process(target=consumer, args=(q, '明小明')).start()
p1 = ctx.Process(target=producer, args=(q, 'AAA', '包子'))
p2 = ctx.Process(target=producer, args=(q, 'BBB', '馒头'))
p1.start()
p2.start()
p1.join()
p2.join()
# 因为有两个消费者,关卡判断队列中是否为空
q.put(None)
q.put(None) # 结束信号
if __name__ == '__main__':
# windows 启动方式
multiprocessing.set_start_method('spawn')
# 获取上下文
ctx = multiprocessing.get_context('spawn')
# 检查这是否是冻结的可执行文件中的伪分支进程。
ctx.freeze_support()
main(ctx)
输出:
2019-10-05 13:41:38,132 [*] AAA 生产包子的编号:1
2019-10-05 13:41:38,142 [*] BBB 生产馒头的编号:1
2019-10-05 13:41:38,720 [*] BBB 生产馒头的编号:2
2019-10-05 13:41:38,734 [*] 明小明 拿了包子的编号:1
2019-10-05 13:41:38,742 [*] 迷心兔 拿了馒头的编号:1
2019-10-05 13:41:38,795 [*] AAA 生产包子的编号:2
2019-10-05 13:41:39,275 [*] BBB 生产馒头的编号:3
2019-10-05 13:41:39,285 [*] 迷心兔 拿了馒头的编号:2
2019-10-05 13:41:39,302 [*] 明小明 拿了包子的编号:2
2019-10-05 13:41:39,405 [*] AAA 生产包子的编号:3
2019-10-05 13:41:39,897 [*] BBB 生产馒头的编号:4
2019-10-05 13:41:39,928 [*] 迷心兔 拿了馒头的编号:3
2019-10-05 13:41:40,122 [*] 明小明 拿了包子的编号:3
2019-10-05 13:41:40,192 [*] AAA 生产包子的编号:4
2019-10-05 13:41:40,605 [*] 迷心兔 拿了馒头的编号:4
2019-10-05 13:41:40,675 [*] BBB 生产馒头的编号:5
2019-10-05 13:41:40,845 [*] AAA 生产包子的编号:5
2019-10-05 13:41:40,958 [*] 明小明 拿了包子的编号:4
2019-10-05 13:41:41,196 [*] 迷心兔 拿了馒头的编号:5
2019-10-05 13:41:41,456 [*] BBB 生产馒头的编号:6
2019-10-05 13:41:41,465 [*] AAA 生产包子的编号:6
2019-10-05 13:41:41,497 [*] 明小明 拿了包子的编号:5
2019-10-05 13:41:41,944 [*] BBB 生产馒头的编号:7
2019-10-05 13:41:41,971 [*] AAA 生产包子的编号:7
2019-10-05 13:41:42,139 [*] 迷心兔 拿了馒头的编号:6
2019-10-05 13:41:42,304 [*] AAA 生产包子的编号:8
2019-10-05 13:41:42,404 [*] 明小明 拿了包子的编号:6
2019-10-05 13:41:42,420 [*] BBB 生产馒头的编号:8
2019-10-05 13:41:42,821 [*] 迷心兔 拿了馒头的编号:7
2019-10-05 13:41:42,904 [*] AAA 生产包子的编号:9
2019-10-05 13:41:42,970 [*] 明小明 拿了包子的编号:7
2019-10-05 13:41:43,179 [*] BBB 生产馒头的编号:9
2019-10-05 13:41:43,619 [*] AAA 生产包子的编号:10
2019-10-05 13:41:43,629 [*] BBB 生产馒头的编号:10
2019-10-05 13:41:43,719 [*] 迷心兔 拿了包子的编号:8
2019-10-05 13:41:43,747 [*] 明小明 拿了馒头的编号:8
2019-10-05 13:41:44,636 [*] 迷心兔 拿了包子的编号:9
2019-10-05 13:41:44,702 [*] 明小明 拿了馒头的编号:9
2019-10-05 13:41:45,368 [*] 明小明 拿了包子的编号:10
2019-10-05 13:41:45,450 [*] 迷心兔 拿了馒头的编号:10