赞
踩
解耦
# Author:SFL from multiprocessing import Process from multiprocessing import Queue # 生产者 def pro(q:Queue): for i in range(1000): q.put("对面谁上单 %i"%(i)) print("对面谁上单 %i"%(i)) # 放完了所有数据以后,放一个 None ,作为结束的标志 q.put(None) # 消费者 def con(q:Queue): i = 0 while 1: r = q.get() if r: print("你爹 %i"%(i)) i = i+1 else : break if __name__ == '__main__': # 缓冲区 : 队列 ( 长度 5 ) q = Queue(5) p1 = Process(target=pro, args=(q,)) p2 = Process(target=con, args=(q,)) p1.start() p2.start()
对面谁上单 0
对面谁上单 1
对面谁上单 2
对面谁上单 3
对面谁上单 4
你爹 0
对面谁上单 5
你爹 1
你爹 2
你爹 3
你爹 4
你爹 5
对面谁上单 6
对面谁上单 7
# Author:SFL from multiprocessing import Process from multiprocessing import Queue # 生产者 def pro(q:Queue): for i in range(1000): q.put("对面谁上单 %i"%(i)) print("对面谁上单 %i"%(i)) # 消费者 def con(q:Queue): i = 0 while 1: r = q.get() if r: print("你爹 %i"%(i)) i = i+1 else : break if __name__ == '__main__': # 缓冲区 : 队列 ( 长度 5 ) q = Queue(5) p1 = Process(target=pro, args=(q,)) p2 = Process(target=con, args=(q,)) p1.start() p2.start() # 让 p1 进程,优先于主进程 p1.join() q.put(None)
# Author:SFL from multiprocessing import Process from multiprocessing import Queue from multiprocessing import JoinableQueue # 生产者 def pro(q:JoinableQueue): for i in range(1000): q.put(i) print("对面谁上单 %i"%(i)) # 等着其他进程,将队列中的消息都消费掉 q.join() # 消费者 def con(q:JoinableQueue): while 1: r = q.get() print("你爹 %i"%(r)) # 本次消息消费结束 q.task_done() if __name__ == '__main__': # 缓冲区 : 队列 ( 长度 5 ) q = JoinableQueue(5) p1 = Process(target=pro, args=(q,)) p2 = Process(target=pro, args=(q,)) c1 = Process(target=con, args=(q,)) c2 = Process(target=con, args=(q,)) c3 = Process(target=con, args=(q,)) c1.daemon = True c2.daemon = True c3.daemon = True p1.start() p2.start() c1.start() c2.start() c3.start() # 生产者必须在主进程之前执行,主进程不可以提前结束 p1.join() p2.join()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。