管道:是python多進程中一種交換數據的方式python
1 from multiprocessing import Process,current_process,Queue,Pipe 2 import time 3 import pickle 4 5 def func_left(q,left): 6 for a in range(5000): 7 b = q.get()#從隊列中獲取數據 8 print('向右管道發送數據',b) 9 msg = pickle.dumps(b)#給右管道發送數據 數據是序列化以後的數據 10 # left.send(msg)#發送數據 11 12 13 def func_right(q,right): 14 for a in range(5000): 15 #從隊列中獲取數據 16 msg = pickle.loads(right.recv())#從右管道接受數據 數據是反序列化以後的數據 17 print('接受到左管道發送的數據',msg)#打印出接受的數據 18 19 20 21 22 23 def main(): 24 q = Queue()#新創建一個queue共享數據 25 for a in range(10001): 26 q.put(a) 27 left,right = Pipe()#創建雙管道 28 p1 = Process(target = func_left,name = '左管道',args=(q,left)) 29 p2 = Process(target = func_right,name = '右管道',args=(q,right)) 30 p1.start() 31 p2.start() 32 33 34 if __name__ == '__main__': 35 main()
管道默認是阻塞狀態,雙通管道spa