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模块。