python threads can only be started once
我的代码:
import threading
import time
def test1():
while True:
print '111111111111'
time.sleep(2)
def test2():
while True:
print '22222222222'
time.sleep(10)
print '222222222222end'
break
return
def test3():
#获取所有线程
thread_list_all = threading.enumerate()
while True:
thread_list1 = threading.enumerate()
thread_list_number = len(thread_list1)
#如果有线程死掉
if thread_list_number < 4:
#查看哪个线程死掉
dead_thread = list(set(thread_list_all).difference(set(thread_list1)))
for item_thread in dead_thread:
print item_thread.getName(),'666666666666'
#重新启动线程
item_thread.start()
# item_thread.join()
time.sleep(1)
t1 = threading.Thread(target=test1,name=test1)
t2 = threading.Thread(target=test2,name=test2)
t3 = threading.Thread(target=test3,name=test3)
t1.start()
t2.start()
t3.start()
t1.join()
t2.join()
t3.join()
运行报错:
111111111111
22222222222
111111111111
111111111111
111111111111
111111111111
222222222222end
111111111111
<function test2 at 0x7f8df4c180c8> 666666666666
Exception in thread <function test3 at 0x7f8df4c18140>:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/home/freedom/work/app/sem/testvivo.py", line 28, in test3
item_thread.start()
File "/usr/lib/python2.7/threading.py", line 730, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
请问我如何才能监控我的线程呢?如果某个线程死掉了,就让他再重新启动。我上面的代码,如果线程3死掉了,就没办法监控了,该如何改我的代码呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
已解决: