结合process进程,实现进程之间的通讯Queue,稍微复杂的运用
#在父进程中创建两个子进程,一个往Queue写数据,一个从Queue里读数据 from multiprocessing import Queue,Process import time,random #往消息队列中写入数据 写入的进程 通过消息队列Queue 作为中间人来实现 def write(q): for value in ["A","B","C","D"]: print('Put %s to queue...'%value) q.put(value) time.sleep(random.random()) #从消息队列中读取数据 读取的进程 def read(q): # time.sleep(1) # count = q.qsize() # print(count) # for i in range(4): while True: if not q.empty(): value = q.get() # print(value) print('Get %s from queue...'%value) time.sleep(random.random()) # else: # break if __name__ == "__main__": #生成一个队列q 可以放无限个消息 q = Queue() pw = Process(target=write,args=(q,)) pr = Process(target=read,args=(q,)) pw.start() pr.start()