python进程之间如何通信

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

1、思路

Process之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。

2、实例

以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据。

frommultiprocessingimportProcess,Queue
importos,time,random

#写数据进程执行的代码:
defwrite(q):
print('Processtowrite:%s'%os.getpid())
forvaluein['A','B','C']:
print('Put%stoqueue...'%value)
q.put(value)
time.sleep(random.random())

#读数据进程执行的代码:
defread(q):
print('Processtoread:%s'%os.getpid())
whileTrue:
value=q.get(True)
print('Get%sfromqueue.'%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()
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。