Discuss / Python / 只是把老师代码敲了一下,得到运行结果。

只是把老师代码敲了一下,得到运行结果。

Topic source

#jincheng1.py 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,))
pr = Process(target=read,args=(q,))
#启动子进程pw,写入
pw.start()
#启动子进程pr,读取
pr.start()
#等待pw结束:
pw.join()
#pr进程里是死循环,无法等待其结束,只能强行终止:
pr.terminate()


运行结果:
Process to write: 901

Process to read: 902 put A to queue... Get A from queue. put B to queue... Get B from queue. put C to queue... Get C from queue.


  • 1

Reply