进程间的通信

方式1 queue队列 先进先出

进程之间默认是没有关联的,进程间的通信就是解决这个问题

from multiprocessing import Queue, Process这是解决普通进程间的通信
from multiprocessing import Manager, Pool这是解决进程间的通信

queue是阻塞的

from multiprocessing import Queue, Process
import os
import time

def write(q):
for value in [1, 2, 3]:
print("put %d to queue"%value)
q.put(value)
time.sleep(1)

def read(q):
while True:
if not q.empty():
value = q.get()
print("get %d from queue" % value)
time.sleep(1)
else:
break

if __name__ == "__main__":
queue =Queue()
pw = Process(target= write, args=(queue,)) ##这里就是把queue当作一个参数穿了进去。这样两个进程就和同一个queue相关联
pr = Process(target=read, args=(queue,))
pw.start()
pw.join()
pr.start()
pr.join()
print("complete")
Result:

put 1 to queue
put 2 to queue
put 3 to queue
get 1 from queue
get 2 from queue
get 3 from queue
complete

 

进程池之间的通信

from multiprocessing import Manager, Pool
import os
import time

def write(q):
for value in [1, 2, 3]:
print("put %d to queue"%value)
q.put(value)
time.sleep(1)

def read(q):
#while True:
#if not q.empty():
#value = q.get()
# print("get %d from queue" % value)
# time.sleep(1)
#else:
#break
  
  for value in range(q.qsize()):
  print("get %d from queue" % q.get())


if __name__ == "__main__":
q = Manager().Queue() #使用Manager中的Queue来初始化
po = Pool()
po.apply(write,(q,))#使用阻塞时创建进程, 这样就不用在read中使用死循环了
po.apply(read,(q,))
po.close()
po.join()
print("complete")

进程间的通信

上一篇:WPF实现消息中心


下一篇:Linux云计算-03_必备基础命令