Skip to content
Advertisement

How to close all the processes one by one in a program that operates with multiprocessing by means of an ‘if’ validation found in one of them process?

JavaScript

I need that when the variable text is equal to "Close your program" the 3 active processes(p1,p2,p3) are closed.

I have tried to do something like this:

JavaScript

But it is not working for me, and I would need a better code that allows me to close them one by one in that code block if text is equal to "Close your program".

What should I do so that under that condition all the processes are closed one by one?

Advertisement

Answer

You could try the following Event-based solution (but there are even simpler solutions to follow):

Have main_process pass to audio_listening an additional argument, finish_state:

JavaScript

Note that it is now main_process that is creating the finish_state multiprocessing.Event instance; there appears to be no need for it to be passed as an argument. When the event is set, the main process will terminate the subprocesses that it has created.

Then in audio_processing:

JavaScript

There are even two simpler alternatives that do not even require an Event variable:

The audio_process process is in an infinite loop until it either gets a “Close your program” message or it gets an exception. In both cases it terminates and presumably we then want the other two processes to terminate, also. Therefore, the main process can just issue a call to p2.join() after it has started all the other processes in order to wait for the audio_process process to complete and then either:

  1. Call p1.terminate() followed by p3.terminate().
  2. Or start processes p1 and p3 specifying daemon=True, e.g. p1 = multiprocessing.Process(target=capture_cam, args=(conn1, conn1b), daemon=True). Being daemon processes they will now automatically terminate as soon as the main process terminates. Therefore, there is no need to call terminate on these processes.
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement