多进行执行某些任务的时候,希望进程有心跳信号来判断进程是否还存在。同时希望多进程情况下,主进程死亡后,没有游离的孤儿进程/线程。避免出现主进程退出后,依然后无法终止的程序在执行。
(进程之间共享变量,通信)
使用multiprocessing.Event()方法实现。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import multiprocessing
import threading
import time
import signal


def heart_thread(stop_signal):
while stop_signal.is_set():
print("heart")
time.sleep(1)


def test_process(stop_signal):
get_thread = threading.Thread(target=heart_thread, args=(stop_signal, ))
get_thread.start()
while stop_signal.is_set():
print("Data_process")
time.sleep(2)
print("退出进程")


def main(stop_signal):
try:
process_list = []
for i in range(3):
print(stop_signal.is_set())
get_process = multiprocessing.Process(target=test_process, args=(stop_signal, ))
get_process.start()
process_list.append(get_process)
while stop_signal.is_set():
time.sleep(3)
except Exception as e:
print(e)


def exits(signum, frame):
global stop_signal_event
stop_signal_event.clear()
print("Exit!!!!")


if __name__ == '__main__':
signal.signal(signal.SIGINT, exits)
signal.signal(signal.SIGTERM, exits)
stop_signal_event = multiprocessing.Event()
stop_signal_event.set()
main(stop_signal_event)

执行效果:
运行后执行Ctrl+C触发终止,执行exits()方法
请使用Linux系统终端执行