If there is no need to end the process immediately pB
is possible with the method terminate()
signaling from one process to another that is finalized by passing its reference through the parameters args
or kwargs
of the class constructor Process
.
from multiprocessing import Process
#Parâmetro p é o processo que será finalizado ao termino dessa função.
def a(p):
while True:
print('a')
break
p.terminate() #Termina o processo p.
def b():
while True:
print('b')
#Troca a ordem de criação dos processos para que a referência pB fique disponível a pA no momento de sua criação.
pB = Process(target=b)
pA = Process(target=a,kwargs={"p":pB})
pB.start() #pB é inicializado primeiro pois do contrário pA pode terminar antes de pB começar.
pA.start()
pA.join()
pB.join()
Unfortunately reverse the reasoning to test within pB
if the process pA
is still alive with is_alive()
does not work because only the parent process can test your children:
#Esse código irá gerar erro...
from multiprocessing import Process
def a():
while True:
print('a')
break
def b(p):
while p.is_alive():
print('b')
pA = Process(target=a)
pB = Process(target=b, kwargs={"p": pA})
pA.start()
pB.start()
pA.join()
pB.join()
Process Process-2:
Traceback (most recent call last):
File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
self.run()
File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
self._target(*self._args, **self._kwargs)
File "main.py", line 9, in b
while p.is_alive():
File "/usr/lib/python3.8/multiprocessing/process.py", line 160, in is_alive
assert self._parent_pid == os.getpid(), 'can only test a child process'
AssertionError: can only test a child process
But the verification can be done in the main process where both pA
and pB
are child processes:
from multiprocessing import Process
def a():
i = 0
while i < 100:
print('a')
i+=1
def b():
while True:
print('b')
pA = Process(target=a)
pB = Process(target=b)
pB.start()
pA.start()
while pA.is_alive():
pass
pB.terminate()
pA.join()
pB.join()
maybe using the function quit() at the end of the two
– João Henrique
I will try to store the processes made in a list and pass this list as parameter and then terminate in each one. I will test
– NoFace