我正在尝试为 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
从以下角度来看,这种行为是有道理的threading
和 Python 本身,但这让我的工作变得更加困难。因此,我实现了一个解决方案,使用字典来存储初始线程并将其复制到新对象并在必要时启动它。不幸的是这也不起作用。
这是一个基本示例:
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')
}
threads = [copy(t) for t in thread_dict.values()]
for t in threads:
t.start()
for i in range(len(threads)):
if not threads[i].isAlive():
temp = thread_dict[threads[i].name]
threads[i] = deepcopy(temp)
threads[i].start()
thread(i).join(5)
返回:
I'm thread a
I'm thread b
Traceback (most recent call last):
File "main_test.py", line 25, in <module>
threads[i] = deepcopy(temp)
File "c:\Python34\lib\copy.py", line 182, in deepcopy
y = _reconstruct(x, rv, 1, memo)
... (there's about 20 lines of traceback within copy)
File "c:\Python34\lib\copyreg.py", line 88, in __newobj__
return cls.__new__(cls, *args)
TypeError: object.__new__(_thread.lock) is not safe, use _thread.lock.__new__()
所以显然threading
对象复制不安全...是否有办法重新启动线程而不重新创建整个对象?