Python的线程控制类

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用

下面是一个基础的python线程控制类

#!/usr/bin/env python
"""
testthread.py
An example of an idiom for controling threads

Doug Fort
http://www.dougfort.net
"""

import threading

class TestThread(threading.Thread):
    """
    A sample thread class
    """

    def __init__(self):
        """
        Constructor, setting initial variables
        """
        self._stopevent = threading.Event()
        self._sleepperiod = 1.0

        threading.Thread.__init__(self, name="TestThread")

    def run(self):
        """
        overload of threading.thread.run()
        main control loop
        """
        print "%s starts" % (self.getName(),)

        count = 0
        while not self._stopevent.isSet():
            count += 1
            print "loop %d" % (count,)
            self._stopevent.wait(self._sleepperiod)

        print "%s ends" % (self.getName(),)

    def join(self,timeout=None):
        """
        Stop the thread
        """
        self._stopevent.set()
        threading.Thread.join(self, timeout)

if __name__ == "__main__":
    testthread = TestThread()
    testthread.start()

    import time
    time.sleep(10.0)

    testthread.join()

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇: iOS获取状态栏和导航栏尺寸(宽度和高度)

下一篇:PHP 获取指定URl页面中所有链接