进程之间如何进行通信?
队列:
# 生产者 def producer(name, food, q): for i in range(20): time.sleep(random.random()) f = "%s 制作了的第%s个%s" % (name, i, food) print(f) # 将数据放入队列中 q.put(f) # 消费者 def chibaozi(name, q): while 1: # 在队列中取值 food = q.get() # 不能用字符形式格式,需要用is关键字才能和none配合 if food is None: break print("%s 消费了 %s" % (name, food)) if __name__ == '__main__': # 创建一个队列 q = Queue() # 生产者 qq = Process(target=producer, args=('Mark', '包子', q)) qq1 = Process(target=producer, args=('Riven', '馒头', q)) # 消费之 qq2 = Process(target=chibaozi, args=('黄埔', q)) qq3 = Process(target=chibaozi, args=('佘义', q)) # 统一启动子进程 qq.start() qq1.start() qq2.start() qq3.start() # 先执行子程序,后执行主程序代码 qq.join() qq1.join() # 放入None 让消费者跳出循环 q.put(None) q.put(None)
管道:
from multiprocessing import Manager from multiprocessing import Process from multiprocessing import Lock def main(dic,lock): # 加锁 lock.acquire() dic['count'] -= 1 print('子进程', dic) lock.release() if __name__ == "__main__": # 虽然进程间数据独立,但可以通过Manager实现数据共享,事实上Manager的功能远不止于此 m = Manager() lock = Lock() # 放入一个字典 dic = m.dict({"count": 100}) for i in range(20): p = Process(target=main, args=(dic,lock)) p.start() p.join() print('测试', dic)