这是一个简单的示例:
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'])
如何使消息进入双端队列,但仍在单独的进程中运行推送功能?
答案 0 :(得分:1)
您可以通过使用旨在在进程之间共享数据的多处理队列对象来共享数据:
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")
让我知道是否有帮助,随时提出问题。
答案 1 :(得分:1)