멀티프로세스로 돌리는 python 예쁘게 죽이는 법
조회수 1496회
리눅스가 아닌 윈도우 환경에서 multiprocess 를 활용하여 멀티코어를 활용하고자 하는데,
잘못해서 인터럽트를 걸면 메인 프로세스만 인터럽트가 걸리고 나머지는 뭔가 무한루프처럼 계속 도는 일이 발생하곤 합니다.
8코어 16쓰레드면, 15개가 살아남아서 뒤에서 계속 무언가 CPU를 먹고 있는데,
지금은 이걸 하나하나 작업관리자에서 찾아서 죽여주고 있는데, 이게 아니라 무언가 예쁘게 일괄 죽이는 방법이 있을 것 같습니다.
노하우 공유 좀 부탁드립니다.
1 답변
-
실행 코드
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')
실행결과(
^C
= 키보드인터럽트)<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
실행때의 프로세스
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
키보드 인터럽트 이후 프로세스
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
KeyboardInterrupt Exception
발생시에해당 프로세스를
terminate()
해주면 됩니당.
댓글 입력