我正在尝试为Python 3.4中的项目制作线程飞行软件,其中我需要线程重新启动,以防在传感器读取期间发生I/O错误或其他类似的侥幸崩溃.因此,我正在制作一个看门狗来检查线程是否已经死亡并重新启动它们.
起初我试图检查线程是否不再存在并重新启动它,这样做:
>>> if not a_thread.isAlive():
... a_thread.start()
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "c:\Python34\lib\threading.py", line 847, in start
raise RuntimeError("threads can only be started once")
RuntimeError: threads can only be started once
Run Code Online (Sandbox Code Playgroud)
从threadingPython本身的角度来看,这种行为是有道理的,但这使我的工作更加困难.所以我使用字典实现了一个解决方案来存储初始线程并将其复制到一个新对象并在必要时启动它.不幸的是,这也不起作用.这是一个基本的例子:
import threading
import logging
import queue
import time
from copy import copy, deepcopy
def a():
print("I'm thread a")
def b():
print("I'm thread b")
# Create thread objects
thread_dict = {
'a': threading.Thread(target=a, name='a'),
'b': threading.Thread(target=b, name='b')
} …Run Code Online (Sandbox Code Playgroud)