python停止线程?暂停?

Python 通过threading.Event()产生一个event对象。event对象维护一个内部标志(标志初始值为False),通过set()将其置为True。wait(timeout)则用于堵塞线程直至Flag被set(或者超时,可选的),isSet()用于查询标志位是否为True,Clear()则用于清除标志位(使之为False)。

import threading 
import time 

class A(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.__running=threading.Event()
        self.__running.set()
    def run(self):
        for i in range(10):
            if self.__running.isSet():
                print i 
                time.sleep(1)
            else:
                break
    def stop(self):
        self.__running.clear()



if __name__=='__main__':
    while (1):
        a=A()
        a.setDaemon(True)
        a.start()
        time.sleep(5)
        a.stop()
#!/usr/bin/env python
# coding: utf-8

import threading
import time


class Job(threading.Thread):

    def __init__(self, *args, **kwargs):
        super(Job, self).__init__(*args, **kwargs)
        self.__flag = threading.Event()     # 用于暂停线程的标识
        self.__flag.set()       # 设置为True
        self.__running = threading.Event()      # 用于停止线程的标识
        self.__running.set()      # 将running设置为True

    def run(self):
        while self.__running.isSet():
            self.__flag.wait()      # 为True时立即返回, 为False时阻塞直到内部的标识位为True后返回
            print time.time()
            time.sleep(1)

    def pause(self):
        self.__flag.clear()     # 设置为False, 让线程阻塞

    def resume(self):
        self.__flag.set()    # 设置为True, 让线程停止阻塞

    def stop(self):
        self.__flag.set()       # 将线程从暂停状态恢复, 如何已经暂停的话
        self.__running.clear()        # 设置为False    

if __name__ == '__main__':
    a = Job()
    a.start()
    time.sleep(3)
    a.pause()
    time.sleep(3)
    a.resume()
    time.sleep(3)
    a.pause()
    time.sleep(2)
    a.stop()

链接
raise exception 停止线程的方式还未实现???

你可能感兴趣的:(python停止线程?暂停?)