python学习-循环线程
2015-07-07 17:24
696 查看
近期需要用到线程去执行一个单独的循环任务,必要的时候可以关闭这个任务。在线程中运行关闭没有找到理想的方法,于是自己通过继承线程实现了,感觉比较方便。
先说下正常的使用,方便进行对比。
我使用最直接分方法把状态控制与线程捆绑在一起,只要执行join函数就可以退出任务关闭线程,让使用者没有感觉差异性。
先说下正常的使用,方便进行对比。
import threading def task(): while True: print "hello" sleep(1) t = threading.thread(target = func) t.start() t.join()这里会发现任务一直被挂起无法退出任务和结束线程,那么通过状态控制while的执行是基本的方法
我使用最直接分方法把状态控制与线程捆绑在一起,只要执行join函数就可以退出任务关闭线程,让使用者没有感觉差异性。
class LoopThread(threading.Thread): def __init__(self, group=None, target=None, name=None, args=(), kwargs=None, verbose=None): super(LoopThread,self).__init__() self.excute = False self.__target = target self.__args = args if kwargs is None: kwargs = {} self.__kwargs = kwargs def run(self): try: if self.__target: while self.excute: self.__target(*self.__args, **self.__kwargs) finally: # Avoid a refcycle if the thread is running a function with # an argument that has a member that points to the thread. del self.__target, self.__args, self.__kwargs def loopstart(self,state = True): self.excute = state self.start() def loopjoin(self,timeout=None): self.excute = False self.join(timeout)这里主要的重载了run方法,提供了新的start和join,使用方法与正常的线程一致
import threading def task(): while True: print "hello" sleep(1) t = LoopThread(target = task) t.loopstart(True)#参量控制是否循环执行 sleep(10) t.loopjoin()
这里就循环执行10秒后任务与线程正常退出
相关文章推荐
- 创业公司都在使用的3款Python库
- python和php对比
- Python学习之相关语法
- 多线程C调用python api的陷阱
- Python的函数
- Python可变参数函数用法实例
- Python中的字符串处理
- Python内置函数str()和repr()
- vim中注释多行python代码
- python中中文字符报错解决
- python3.4学习笔记(十八) pycharm 安装使用、注册码、显示行号和字体大小等常用设置
- C#调用Python脚本的简单示例
- python类和继承用法实例
- Python实现合并字典的方法
- 机器学习算法与Python实践之 k均值聚类(k-means)
- python re.search 和 re.match 正则表达式
- pythone-2:用户登录并根据条件查询
- 【python】写在初学python语言之际
- Python变量作用范围实例分析
- [uWSGI] Python threading and locks