# -*- coding:utf-8 -*-
import threading
import psutil
import os
import time
'''
通过 threading.Thread.is_active 判断线程是否退出。
此方法可以用来对程序进行监听,当程序出现异常退出,重启程序。
'''
class MyThread(threading.Thread):
def __init__(self, threadID, name, func, param=None):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.func = func
self.param = param
def run(self):
lock = threading.Lock()
if lock.acquire(): # 加锁
if self.param is None:
self.func() # 调用传进来的函数
else:
self.func(self.param)
print(self.name, time.ctime)
lock.release() # 释放锁
def test_func():
i = 0
while i < 60:
i += 1
print('i : {}'.format(str(i)))
time.sleep(1)
def check_threading(t1):
'''
检测t1 线程是否退出
:param t1:
:return:
'''
while True:
print(threading.Thread.is_alive(t1))
if not threading.Thread.is_alive(t1): # 如果线程退出, 重新创建一个进程
t1 = MyThread(1, 'test_func', test_func)
t1.start()
t1.join()
time.sleep(60)
thread_list = []
t1 = MyThread(1, 'test_func', test_func)
thread_list.append(t1)
thread_list.append(MyThread(2, 'check_threading', check_threading, t1))
for t in thread_list:
t.start()
for t in thread_list:
t.join()