1、作用:进程之间的数据交互
2、常用方法
""" 对象.put() 作用:放入队列一个数据 对象.get() 作用:取队列一个数据,若队列没有值,则阻塞 对象.empty() 作用:判断队列是否为空 对象.full() 作用:判断队列是否为满 """
3、例子
""" 子进程Process-1 和 子进程Process-2进行数据传输 """ from multiprocessing import Queue from multiprocessing import Process def new_put(q): q.put('你好') def new_get(q): ret = q.get() print(ret) if __name__ == '__main__': q = Queue() p = Process(target=new_put, args=(q, )) p.start() print(p.name) g = Process(target=new_get, args=(q, )) g.start() print(g.name)
4、生产者消费者模型
import time import random from multiprocessing import Process from multiprocessing import Queue def producer(name, food, q): for i in range(6): f = '%s生产%s%s' % (name,food, i) print(f) time.sleep(random.randint(1, 3)) q.put(f) def consumer(name, q): while 1: f1 = q.get() if f1 is None: break f = '********************%s吃%s' % (name, f1) print(f) time.sleep(random.randint(1, 2)) if __name__ == '__main__': q = Queue() p = Process(target=producer, args=('tom', '包子', q)) p.start() p2 = Process(target=producer, args=('joker', '馒头', q)) p2.start() c1 = Process(target=consumer, args=('wt', q)) c1.start() c2 = Process(target=consumer, args=('son', q)) c2.start() p.join() p2.join() q.put(None) q.put(None)
优化
import time import random from multiprocessing import Process from multiprocessing import JoinableQueue def producer(name, food, q): for i in range(6): f = '%s生产%s%s' % (name,food, i) print(f) time.sleep(random.randint(1, 3)) q.put(f) q.join() def consumer(name, q): while 1: f1 = q.get() f = '********************%s吃%s' % (name, f1) print(f) time.sleep(random.randint(1, 2)) q.task_done() if __name__ == '__main__': q = JoinableQueue() p = Process(target=producer, args=('tom', '包子', q)) p.start() p2 = Process(target=producer, args=('joker', '馒头', q)) p2.start() c1 = Process(target=consumer, args=('wt', q)) c1.daemon = True c1.start() c2 = Process(target=consumer, args=('son', q)) c2.daemon = True c2.start() p.join() p2.join()
过程:主进程等待->生产者进程,生产者等待->消费者
p.join()->q.join()->c,task_down()
obj.join()
作用:阻塞,直到队列里的所有值被处理,一般在生产者进程中和put()方法一起使用
obj.task_down()
作用:向q.join()发送信号量,表名q.get()的值,已经被处理
注意:给消费者设置守护进程,队列的数据处理完毕后,消费者再执行下去,没有意义