python创建消息队列

实现进程之间的通信

from multiprocessing import Process,Pool,Queue
import os
import time
import random

def write(q):
    for item in 'ABC':
        print('正在往消息队列写入%s'%(item))
        q.put(item)
        time.sleep(random.random())
    
def reader(q):
    while True:
        if not q.empty():
            item = q.get()
            print('从消息队列读出%s'%item)
            time.sleep(random.random())
            
        else:
            break


    
if __name__ == "__main__":
   q = Queue()
   pw = Process(target=write,args=(q,))
   pw.start()
   pw.join()
   pr = Process(target=reader,args=(q,))
   pr.start()
   pr.join()
   print('数据已读完')

进程池创建的队列消息

from multiprocessing import Process,Pool,Queue,Manager
import os
import time
import random

def write(q):
    for item in 'ABC':
        print('正在往消息队列写入%s'%(item))
        q.put(item)
        time.sleep(random.random())
    
def reader(q):
    while True:
        if not q.empty():
            item = q.get()
            print('从消息队列读出%s'%item)
            time.sleep(random.random())
            
        else:
            break


    
if __name__ == "__main__":
   q = Manager().Queue()
   p1 = Pool(3)
   p1.apply(write,(q,))
   p1.apply(reader,(q,))
   p1.close()
   p1.join()
   print('数据已读完')

你可能感兴趣的:(python创建消息队列)