您好,登錄后才能下訂單哦!
1.管道使用
'''
管道Pipe
'''
from multiprocessing import Process,Pipe
def f(conn):
conn.send('child message')#給主進程發送消息
conn.close()
if __name__=='__main__':
parent_conn,child_conn=Pipe()
p=Process(target=f,args=(child_conn,))
p.start()
print(parent_conn.recv())#主進程接收子進程消息
p.join()
2.Manage增強版pipe,可以接收字典,列表等
from multiprocessing import Process,Manager
import os
def f(d,l):#處理字典,列表函數
d[1]='1'
d['2']=2
l.append(os.getpid())
if __name__=="__main__":
manage_data=Manager()
d=manage_data.dict()
l=manage_data.list()
p_list=[]
for i in range(10):#建立10個進程并調用公共函數f
p = Process(target=f, args=(d, l))
p.start()
p_list.append(p)
for res in p_list:
res.join()
print(d)
print(l)
>>:
{1: '1', '2': 2}
[2472, 7972, 9760, 5328, 5488, 12316, 6780, 12592, 6676, 6408]
3.進程池與回調函數
from multiprocessing import Process,Pool
import time
import os
def Foo(i):
time.sleep(2)
print("in process",os.getpid())
return i+100
def Bar(arg):
print("-->exec done:",arg,os.getpid())
if __name__=='__main__':
pool=Pool(processes=2)#同時運行的進程數
print("main process",os.getpid())
for i in range(10):
pool.apply_async(func=Foo,args=(i,),callback=Bar)
pool.close()
pool.join()
>>:
main process 15704
in process 15336
in process 14796
-->exec done: 100 15704
-->exec done: 101 15704
in process 14796
in process 15336
-->exec done: 103 15704
-->exec done: 102 15704
in process 14796
in process 15336
-->exec done: 104 15704
-->exec done: 105 15704
in process 15336
in process 14796
-->exec done: 107 15704
-->exec done: 106 15704
in process 15336
in process 14796
-->exec done: 109 15704
-->exec done: 108 15704
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。