这里有一个简单的例子:
from collections import deque
from multiprocessing import Process
global_dequeue = deque([])
def push():
global_dequeue.append('message')
p = Process(target=push)
p.start()
def pull():
print(global_dequeue)
pull()
输出为deque([](
如果我直接调用push函数,而不是作为一个单独的进程,输出将是deque(['message'](
如何将消息放入deque,但仍在单独的过程中运行推送功能?
您可以使用多处理队列对象共享数据,该对象旨在在进程之间共享数据:
from multiprocessing import Process, Queue
import time
def push(q): # send Queue to function as argument
for i in range(10):
q.put(str(i)) # put element in Queue
time.sleep(0.2)
q.put("STOP") # put poison pillow to stop taking elements from Queue in master
if __name__ == "__main__":
q = Queue() # create Queue instance
p = Process(target=push, args=(q,),) # create Process
p.start() # start it
while True:
x = q.get()
if x == "STOP":
break
print(x)
p.join() # join process to our master process and continue master run
print("Finish")
如果有帮助,请告诉我,随时提问。
您也可以使用管理器来实现这一点。
Python 2:https://docs.python.org/2/library/multiprocessing.html#managers
Python 3:https://docs.python.org/3.8/library/multiprocessing.html#managers
用法示例:
https://pymotw.com/2/multiprocessing/communication.html#managing-共享状态