Reputation: 3
import multiprocessing as mp
def func():
the code inside func
for _ in range(10)
process = mp.Process(target=func)
process.start()
So in the code written above, how would I kill each and individual process when wanted?
Upvotes: 0
Views: 2311
Reputation: 44108
You should probably save the processes in a dict
keyed by the process id (pid
attribute) for fast lookup. Then you can call terminate
on the Process
instance:
import multiprocessing as mp
def func():
...
process_dict = {}
for _ in range(10):
process = mp.Process(target=func)
process.start()
process_dict[process.pid] = process
...
# Kill a process given a pid:
# This also removes the key from the dictionary:
process = process_dict.pop(pid)
process.terminate()
...
# Wait for remaining processes to end:
for process in process_dict.values():
process.join()
The assumption is that the pid belongs to one of the processes that you created (otherwise the pop
operation will raise a KeyError
exception.
The above code assumes you are running under a platform that uses fork
to create new processes (such as Linux) and therefore you do not need to place code that creates new processes within a if __name__ == '__main__':
block. But you really should tag your question with the platform.
Upvotes: 1