簡體   English   中英

對主進程的多處理回調 - Python

[英]Multiprocessing Callbacks to Main Process - Python

有沒有辦法使用多處理從創建的進程回調主進程? 假設我有 main.py,它使用 multiprocessing 創建三個進程,如下所示

from multiprocessing import Process
from child import createNewProcess

def callbackFunction(data):
   print(data)

if __name__ == "__main__"
   process = []
   for i in range(3):
        p = Process(target=createNewProcess, args=(callback,))
        process.append(p)
   [x.start() for x in process]

child.py 看起來像

def createNewProcess(externalCB):
    # do something and call external callback
    data = 10 + 12
    externalCB(data)

我想調用 callbackFunction() ,它在創建的進程的主進程上下文中可用。 但在上面的例子中,它在自己的進程中創建了三個新的 callbackFunction() 對象,並調用在自己的上下文中的對象。

如何使用多處理進程調用主 callbackFunction() 上下文?

使用隊列傳遞適當回調的示例代碼段,並將數據返回到主進程上的線程:

from multiprocessing import Process, Queue, current_process
from threading import Thread
from time import sleep

def foo_process(data, cb_queue, cb):
    print(f"data from process [{current_process().pid}]: {data}")
    sleep(.1) # time to flush stdout so print statement is usually in correct order
              # (may still be out of order on IPython)
    cb_queue.put((cb, data))

def foo_thread(data):
    print(f"data from cb_thread in process [{current_process().pid}]: {data*2}")

def callback_caller(cb_queue):
    for func, *args in iter(cb_queue.get, None): #pass None to exit thread
        func(*args)

if __name__ == "__main__":
    print(f"main pid: [{current_process().pid}]")
    q = Queue()

    p = Process(target=foo_process, args=(3.15, q, foo_thread))
    p.start()
    
    #It's advisable (if possible) to always create processes first then threads.
    #this primarily applies to using "fork", but it's good to know / good habit.
    t = Thread(target=callback_caller, args=(q,))
    t.start()

    p.join()

    q.put(None) #send shutdown signal to callback_caller
    t.join()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM