目前我在主流程下创建了3个流程A,B,C。但是,我想在流程A中启动B和C.这可能吗?
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 :(得分:2)
我建议使用@graph.get_object("me", { fields: [:id, :email, :first_name, :gender, :last_name, :link, :locale, :name, :timezone, :updated_time, :verified]})
个对象来进行同步。它们允许在整个过程中触发一些操作。例如
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
模块。