Python 进程间通信
1 from multiprocessing import Process,Queue 2 import os,time,random 3 4 5 def write(q): 6 print('Process to write:%s' % os.getpid()) 7 for value in ['A','B','C']: 8 print('Put %s to queue...'% value) 9 q.put(value) 10 time.sleep(random.random()) 11 12 13 def read(q): 14 print('Process to read: %s' % os.getpid()) 15 while True: 16 value = q.get(True) 17 print('Get %s from queue'% value) 18 19 if __name__ == '__main__': 20 q = Queue() 21 pw = Process(target=write,args=(q,)) 22 pr = Process(target=read,args=(q,)) 23 pw.start() 24 pr.start() 25 pw.join() 26 pr.terminate()