2

目前我在主進程下創建了3個進程A,B,C。但是,我想在流程A中啓動B和C.這是可能的嗎?AssertionError:只能啓動當前進程創建的進程對象

process.py

from multiprocessing import Process 

procs = {} 
import time 

def test(): 
    print(procs) 
    procs['B'].start() 
    procs['C'].start() 
    time.sleep(8) 

    procs['B'].terminate() 
    procs['C'].termiante() 

    procs['B'].join() 
    procs['C'].join() 




def B(): 
    while True: 
     print('+'*10) 
     time.sleep(1) 
def C(): 
    while True: 
     print('-'*10) 
     time.sleep(1) 


procs['A'] = Process(target = test) 
procs['B'] = Process(target = B) 
procs['C'] = Process(target = C) 

main.py

from process import * 
print(procs) 
procs['A'].start() 
procs['A'].join() 

而且我得到了錯誤的AssertionError :只能啓動由當前進程創建的進程對象

是否有任何替代方法在A中啓動進程B和C?或者讓A發送信號問主進程啓動B和C

+0

檢查'multiprocessing'模塊,嘗試一些內容,然後向我們顯示您的代碼。 –

+0

@AliGajani我嘗試在A中創建這些流程,但這不適合我的情況。 –

回答

2

我會推薦使用Event對象來做同步。他們允許在整個流程中觸發一些操作。例如

from multiprocessing import Process, Event 
import time 

procs = {} 


def test(): 
    print(procs) 

    # Will let the main process know that it needs 
    # to start the subprocesses 
    procs['B'][1].set() 
    procs['C'][1].set() 
    time.sleep(3) 

    # This will trigger the shutdown of the subprocess 
    # This is cleaner than using terminate as it allows 
    # you to clean up the processes if needed. 
    procs['B'][1].set() 
    procs['C'][1].set() 


def B(): 
    # Event will be set once again when this process 
    # needs to finish 
    event = procs["B"][1] 
    event.clear() 
    while not event.is_set(): 
     print('+' * 10) 
     time.sleep(1) 


def C(): 
    # Event will be set once again when this process 
    # needs to finish 
    event = procs["C"][1] 
    event.clear() 
    while not event.is_set(): 
     print('-' * 10) 
     time.sleep(1) 


if __name__ == '__main__': 
    procs['A'] = (Process(target=test), None) 
    procs['B'] = (Process(target=B), Event()) 
    procs['C'] = (Process(target=C), Event()) 
    procs['A'][0].start() 

    # Wait for events to be set before starting the subprocess 
    procs['B'][1].wait() 
    procs['B'][0].start() 
    procs['C'][1].wait() 
    procs['C'][0].start() 

    # Join all the subprocess in the process that created them. 
    procs['A'][0].join() 
    procs['B'][0].join() 
    procs['C'][0].join() 

請注意,這段代碼並不是很乾淨。在這種情況下只需要一個事件。但你應該明白主意。

此外,不再需要進程A,您可以考慮使用回調。如果要鏈接一些異步操作,請參閱concurrent.futures模塊。