#coding:utf-8 from multiprocessing import Process, Queue import os,time,random #通过队列进行进程通信 #写数据 def write(q): print('Process to write (%s)' % os.getpid()) for value in ['A', 'B', 'C']: print('put %s to queue...' % value) q.put(value) time.sleep(random.random()) #读数据 def read(q): print('Process to read (%s)' % os.getpid()) while True: value = q.get(True) print('Get %s from queue' % value) if __name__ == '__main__': # 父进程创建Queue,并传递给子进程 q = Queue() pw = Process(target = write, args = (q,)) #启动子进程pw,写入: pw.start() #等待pw结束 pw.join() pr = Process(target = read, args = (q,)) #启动子进程pr,读取: pr.start() #pr进程是死循环,无法等待结束,只能强制终止 pr.terminate()
运行结果:
Process to write (29287) put A to queue... put B to queue... put C to queue...
pr进程start后你调用terminate,读进程没来得及运行,试一下start后sleep一段时间
我认为楼上说得对
我刚刚试了一下,执行到pr.start()的第一行大概要0.002秒,在pr.start()前加一句应该就能看到结果
pr.start() time.sleep(0.002)
Sign in to make a reply
爱喝白开shui
运行结果: