python 线程重启_在Python中重新启动一个线程

我正在尝试为

Python 3.4中的项目制作线程飞行软件,其中我需要线程重新启动,以防在传感器读取期间发生I / O错误或其他类似的侥幸崩溃.因此,我正在制作一个看门狗来检查线程是否已经死亡并重新启动它们.

起初我试图检查线程是否不再存在并重新启动它,这样做:

>>> if not a_thread.isAlive():

... a_thread.start()

Traceback (most recent call last):

File "", line 2, in

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

从线程和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

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__()

因此,显然线程对象复制是不安全的……无论如何重新启动线程而不是重新创建整个对象?

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值