我正在努力解决多处理问题并将全局True / False变量传递给我的函数。
get_data()完成后,我希望analyze()函数启动并处理数据,而fetch()继续运行。我怎样才能做到这一点? TIA
import multiprocessing
ready = False
def fetch():
global ready
get_data()
ready = True
return
def analysis():
analyse_data()
if __name__ == '__main__':
p1 = multiprocessing.Process(target=fetch)
p2 = multiprocessing.Process(target=analysis)
p1.start()
if ready:
p2.start()
答案 0 :(得分:1)
您应该运行这两个进程并使用共享队列在它们之间交换信息,例如在其中一个进程中发出完成操作的信号。
此外,您需要有一个join()语句才能正确等待您生成的进程的完成。
from multiprocessing import Process, Queue
import time
def get_data(q):
#Do something to get data
time.sleep(2)
#Put an event in the queue to signal that get_data has finished
q.put('message from get_data to analyse_data')
def analyse_data(q):
#waiting for get_data to finish...
msg = q.get()
print msg #Will print 'message from get_data to analyse_data'
#get_data has finished
if __name__ == '__main__':
#Create queue for exchanging messages between processes
q = Queue()
#Create processes, and send the shared queue to them
processes = [Process(target=get_data,args(q,)),Process(target=analyse_data,args=(q,))]
#Start processes
for p in processes:
p.start()
#Wait until all processes complete
for p in processes:
p.join()
答案 1 :(得分:0)
您的示例因以下几个原因无效:
阅读https://docs.python.org/3/library/ipc.html以获得进程间通信的更多可能性