首先使用多线程的方法进行现场通信:
import time
from multiprocessing import Process
from queue import Queue
def producer(queue):
queue.put("a")
time.sleep(2)
def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)
if __name__ == "__main__":
queue = Queue(10)
my_prod = Process(target = producer,args=(queue,))
my_consumer = Process(target = consumer,args=(queue,))
my_prod.start()
my_consumer.start()
my_prod.join()
my_consumer.join()
这种方法是不能用的,需要使用多进程中的queue
import time
from multiprocessing import Process, Queue
def producer(queue):
queue.put("a")
time.sleep(2)
def consumer(queue):
time.sleep(2)
data = queue.get()
print(data)
if __name__ == "__main__":
queue = Queue(10)
my_prod = Process(target = producer,args=(queue,))
my_consumer = Process(target = consumer,args=(queue,))
my_prod.start()
my_consumer.start()
my_prod.join()
my_consumer.join()
共享全局变量是不用进程池
pipe性能更加好
通过pipe实现进程之间的通信
receive_pipe ,send_pipe = Pipe()
pipe只能适用于两个进程
def producer(pipe):
pipe.send("im lizeyi")
def consumer(pipe):
print(pipe.recv())