栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

python

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python

在Python和任何语言中,突然终止线程通常都是一种糟糕的模式。请考虑以下情况:

  • 线程持有必须正确关闭的关键资源
  • 该线程创建了其他几个必须同时终止的线程。

如果你负担得起的话(如果你要管理自己的线程),处理此问题的一种好方法是有一个

exit_request
标志,每个线程定期检查一次,以查看是否该退出。

例如:

import threadingclass StoppableThread(threading.Thread):    """Thread class with a stop() method. The thread itself has to check    regularly for the stopped() condition."""    def __init__(self,  *args, **kwargs):        super(StoppableThread, self).__init__(*args, **kwargs)        self._stop_event = threading.Event()    def stop(self):        self._stop_event.set()    def stopped(self):        return self._stop_event.is_set()

在此代码中,你应

stop()
在希望退出线程时调用它,然后使用来等待线程正确退出
join()
。线程应定期检查停止标志。

但是,在某些情况下,你确实需要杀死线程。一个示例是当你包装一个忙于长时间调用的外部库并且想要中断它时。

以下代码允许(有一些限制)在Python线程中引发

Exception

def _async_raise(tid, exctype):    '''Raises an exception in the threads with id tid'''    if not inspect.isclass(exctype):        raise TypeError("only types can be raised (not instances)")    res = ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid),         ctypes.py_object(exctype))    if res == 0:        raise ValueError("invalid thread id")    elif res != 1:        # "if it returns a number greater than one, you're in trouble,        # and you should call it again with exc=NULL to revert the effect"        ctypes.pythonapi.PyThreadState_SetAsyncExc(ctypes.c_long(tid), None)        raise SystemError("PyThreadState_SetAsyncExc failed")class ThreadWithExc(threading.Thread):    '''A thread class that supports raising exception in the thread from       another thread.    '''    def _get_my_tid(self):        """determines this (self's) thread id        CAREFUL : this function is executed in the context of the caller        thread, to get the identity of the thread represented by this        instance.        """        if not self.isAlive(): raise threading.ThreadError("the thread is not active")        # do we have it cached?        if hasattr(self, "_thread_id"): return self._thread_id        # no, look for it in the _active dict        for tid, tobj in threading._active.items(): if tobj is self:     self._thread_id = tid     return tid        # TODO: in python 2.6, there's a simpler way to do : self.ident        raise AssertionError("could not determine the thread's id")    def raiseExc(self, exctype):        """Raises the given exception type in the context of this thread.        If the thread is busy in a system call (time.sleep(),        socket.accept(), ...), the exception is simply ignored.        If you are sure that your exception should terminate the thread,        one way to ensure that it works is: t = ThreadWithExc( ... ) ... t.raiseExc( SomeException ) while t.isAlive():     time.sleep( 0.1 )     t.raiseExc( SomeException )        If the exception is to be caught by the thread, you need a way to        check that your thread has caught it.        CAREFUL : this function is executed in the context of the        caller thread, to raise an excpetion in the context of the        thread represented by this instance.        """        _async_raise( self._get_my_tid(), exctype )

(基于Tomer Filiba的Killable Threads。有关return值的引用PyThreadState_SetAsyncExc似乎来自旧版本的Python。)

如文档中所述,这不是灵丹妙药,因为如果线程在Python解释器之外很忙,它将无法捕获中断。

此代码的一个很好的用法模式是让线程捕获特定的异常并执行清理。这样,你可以中断任务并仍然进行适当的清理。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/367676.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号