首页 > 编程 > Python > 正文

python 多线程重启方法

2019-11-25 13:16:23
字体:
来源:转载
供稿:网友

python 多线程程序运行中,会出现由于异常而导致某线程停止的情况,为了保证程序的稳定运行,需要自动重启down掉的线程.

python Threading类有一个setName()的方法,可以为线程设置名字。

threading.enumerate()可以获取当前的线程对象。

自动重启线程的思路如下:

1.使用setName()每个线程设置名字;

2.在初始化运行时使用threading.enumerate()获取当前所有线程对象,保存为初始线程组;

3.隔一段时间使用threading.enumerate()获取当前所有线程对象,与初始线程组对比,如果某个name缺失,则重新start。

下面举个例子:

#coding:utf-8import threadinglist_ip=['1.1.1.1','2.2.2.2','3.3.3.3'] #一组ip列表def printIP(ip):  print ip#每180s获取当前线程名,并跟初始线程组比较,某一线程停止后自动运行def checkThread(sleeptimes=180,initThreadsName=[]):  for i in range(0,10080):#循环运行    nowThreadsName=[]#用来保存当前线程名称    now=threading.enumerate()#获取当前线程名    for i in now:      nowThreadsName.append(i.getName())#保存当前线程名称    for ip in initThreadsName:      if ip in nowThreadsName:        pass #当前某线程名包含在初始化线程组中,可以认为线程仍在运行      else:        print '==='+ip,'stopped,now restart'        t=threading.Thread(target=printIP,args=(ip,))#重启线程        t.setName(ip)#重设name        t.start()    time.sleep(sleeptimes)#隔一段时间重新运行,检测有没有线程downif __name__ == '__main__':  threads=[]  initThreadsName=[]#保存初始化线程组名字  for ip in list_ip:    t=threading.Thread(target=printIP,args=(ip,))    t.setName(ip)    threads.append(t)  for t in threads:    t.start()  init=threading.enumerate()#获取初始化的线程对象  for i in init:    initThreadsName.append(i.getName())#保存初始化线程组名字  check=threading.Thread(target=checkThread,args=(180,initThreadsName))#用来检测是否有线程down并重启down线程  check.setName('Thread:check')  check.start()

以上这篇python 多线程重启方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表