最新公告
  • 欢迎您光临网站无忧模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • python多线程爬虫如何退出

    正文概述    2020-03-29   250

    python多线程爬虫如何退出

    解决方案 · 壹

    一个比较nice的方式就是每个线程都带一个退出请求标志,在线程里面间隔一定的时间来检查一次,看是不是该自己离开了!

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

    在这部分代码所示,当你想要退出线程的时候你应当显示调用stop()函数,并且使用join()函数来等待线程合适地退出。线程应当周期性地检测停止标志。

    然而,还有一些使用场景中你真的需要kill掉一个线程:比如,当你封装了一个外部库,但是这个外部库在长时间调用,因此你想中断这个过程。

    相关推荐:《Python基础教程》

    解决方案 · 貳

    接下来的方案是允许在python线程里面raise一个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(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(tid, 0)
            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 )

    正如注释里面描述,这不是啥“灵丹妙药”,因为,假如线程在python解释器之外busy,这样子的话终端异常就抓不到啦~

    这个代码的合理使用方式是:让线程抓住一个特定的异常然后执行清理操作。这样的话你就能终端一个任务并能合适地进行清除。

    解决方案 · 叁

    假如我们要做个啥事情,类似于中断的方式,那么我们就可以用thread.join方式。

    join的原理就是依次检验线程池中的线程是否结束,没有结束就阻塞直到线程结束,如果结束则跳转执行下一个线程的join函数。

    先看看这个:

    1. 阻塞主进程,专注于执行多线程中的程序。

    2. 多线程多join的情况下,依次执行各线程的join方法,前头一个结束了才能执行后面一个。

    3. 无参数,则等待到该线程结束,才开始执行下一个线程的join。

    4. 参数timeout为线程的阻塞时间,如 timeout=2 就是罩着这个线程2s 以后,就不管他了,继续执行下面的代码。

    # coding: utf-8
    # 多线程join
    import threading, time  
    def doWaiting1():  
        print 'start waiting1: ' + time.strftime('%H:%M:%S') + "\n"  
        time.sleep(3)  
        print 'stop waiting1: ' + time.strftime('%H:%M:%S') + "\n" 
    def doWaiting2():  
        print 'start waiting2: ' + time.strftime('%H:%M:%S') + "\n"   
        time.sleep(8)  
        print 'stop waiting2: ', time.strftime('%H:%M:%S') + "\n"  
    tsk = []    
    thread1 = threading.Thread(target = doWaiting1)  
    thread1.start()  
    tsk.append(thread1)
    thread2 = threading.Thread(target = doWaiting2)  
    thread2.start()  
    tsk.append(thread2)
    print 'start join: ' + time.strftime('%H:%M:%S') + "\n"   
    for tt in tsk:
        tt.join()
    print 'end join: ' + time.strftime('%H:%M:%S') + "\n"

    默认join方式,也就是不带参,阻塞模式,只有子线程运行完才运行其他的。

    1、 两个线程在同一时间开启,join 函数执行。

    2、waiting1 线程执行(等待)了3s 以后,结束。

    3、waiting2 线程执行(等待)了8s 以后,运行结束。

    4、join 函数(返回到了主进程)执行结束。

    这里是默认的join方式,是在线程已经开始跑了之后,然后再join的,注意这点,join之后主线程就必须等子线程结束才会返回主线。

    join的参数,也就是timeout参数,改为2,即join(2),那么结果就是如下了:

    两个线程在同一时间开启,join 函数执行。

    wating1 线程在执行(等待)了三秒以后,完成。

    join 退出(两个2s,一共4s,36-32=4,无误)。

    waiting2 线程由于没有在 join 规定的等待时间内(4s)完成,所以自己在后面执行完成。


    下载网 » python多线程爬虫如何退出

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元