How to kill Python prettily by multiprocessing

Asked 2 years ago, Updated 2 years ago, 106 views

I would like to utilize multi-core in a Windows environment other than Linux.

If you accidentally interrupt, only the main process will be interrupted, and the rest will continue to spin like an infinite loop.

Eight-core 16 threads, 15 survived and kept eating CPU behind you

Now, I'm finding it one by one from the task manager and killing it, but I think there's a way to kill it in a pretty way.

Please share your know-how.

python multiprocessing

2022-09-21 11:17

1 Answers

Execution Code

import time
from multiprocessing import Process

def f(name):
    while(True):
        print('hello', name)
        time.sleep(10)

if __name__ == '__main__':
    a = ['Bob','John','Howoni']
    ps = []
    for i in a:
        p = Process(target=f, args=(i,))
        ps.append(p)
        p.start()
        print(p, 'start')

    try:
        for i in ps:
            i.join()
    except KeyboardInterrupt:
        for i in ps:
            i.terminate()
            print(i, 'terminate')

Execution result (^C = keyboard interrupt)

<Process(Process-1, started)> start
hello Bob
<Process(Process-2, started)> start
hello John
<Process(Process-3, started)> start
hello Howoni
hello Bob
hello John
hello Howoni
^C<Process(Process-1, started)> terminate
Process Process-3:
Process Process-2:
<Process(Process-2, started)> terminate
<Process(Process-3, started)> terminate

Runtime Process

howoni      45     7  0 21:02 tty1     00:00:00 python3
howoni     225     7  5 21:18 tty1     00:00:00 python3 456.py
howoni     226   225  0 21:18 tty1     00:00:00 python3 456.py
howoni     227   225  0 21:18 tty1     00:00:00 python3 456.py
howoni     228   225  0 21:18 tty1     00:00:00 python3 456.py
howoni     230    71  0 21:18 tty2     00:00:00 grep --color=auto python

Post-keyboard Interrupt Process

howoni      45     7  0 21:02 tty1     00:00:00 python3
howoni     232    71  0 21:18 tty2     00:00:00 grep --color=auto python

When KeyboardInterruptException occurs

You can terminate() this process.


2022-09-21 11:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.