python进程之间如何通信
python进程之间如何通信
本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。
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()
以上就是python进程之间通信的方法,希望能对大家有所帮助。更多Python学习教程请关注IT培训机构:千锋教育。

相关推荐HOT
更多>>
python正则表达式中的零宽断言
python正则表达式中的零宽断言1、概念有些元字符不匹配任何字符,只是简单的表示成功或失败,所以这些字符也叫零宽断言。2、符号举例(1)|或操作...详情>>
2023-11-14 11:35:03
python方法的绑定和未绑定
python方法的绑定和未绑定1、说明未绑定对象的方法:无self参数的方法,通过定义类调用函数,返回未绑定self的方法。绑定对象的方法:带self参...详情>>
2023-11-14 09:53:02
python海象运算符的使用
python海象运算符的使用1、在判断条件下允许操作。在一定程度上简化了代码,但降低了可读性。i=len((l:=[1,2,3]))#先对l进行赋值,在对i赋值whi...详情>>
2023-11-14 02:38:21
pythonelif语句报错是什么原因
python的else和elif语句也可以叫做子句,因为它们不能独立使用,两者都是出现在if、for、while语句内部的。else子句可以增加一种选择;而elif子...详情>>
2023-11-13 21:46:35热门推荐
技术干货






