【Python@Thread】threading模块
theading模块的Thread类
属性:
name 线程名
ident 线程标识符
daemon 布尔值,标示是否为守护线程
方法:
__init__(target=None, name=None, *args=(), **kwargs={})
start() 开始执行线程
run() 定义线程功能的方法
join(timeout=None) 阻塞线程,等待被唤醒,好于忙等待
Thread类的使用主要有三种方法:
1.创建Thread实例,传给其一个参数
2.创建Thread实例,传给其一个可调用的类实例
3.派生Thread子类,创建子类实例
下面介绍这三种用法:
1.创建Thread实例,传给其一个参数
from threading import Thread
from time import ctime, sleep loops = [4, 2] def loop(nloop, nsec):
print('loops ', nloop, 'starting at:', ctime())
sleep(nsec)
print('loop', nloop, 'end at:', ctime()) def main():
print('starting at:', ctime())
threads = [] for i in range(len(loops)):
t = Thread(target=loop, args=(i,loops[i]))
threads.append(t) ###保存类实例 for i in range(len(loops)):
threads[i].start() ###同时启动类实例 for i in range(len(loops)):
threads[i].join() ###保持主线程切出 print('all done at:', ctime()) if __name__ == '__main__':
main()
运行结果:
starting at: Mon Dec 19 23:29:58 2016
loops 0 starting at: Mon Dec 19 23:29:58 2016
loops 1 starting at: Mon Dec 19 23:29:58 2016
loop 1 end at: Mon Dec 19 23:30:00 2016
loop 0 end at: Mon Dec 19 23:30:02 2016
all done at: Mon Dec 19 23:30:02 2016
方法1,传入函数创建类实例,不用人为设置锁,释放锁
方法二:传入可调用类创建类实例(用法感觉有点像装饰器)
from threading import Thread
from time import ctime, sleep loops = [4, 2] class TFun():
def __init__(self, name, func, args):
self.name = name
self.func = func
self.args = args def __call__(self):
return self.func(*self.args) def loop(nloop, nsec):
print('loop ', nloop, 'at:', ctime())
sleep(nsec)
print('loop ', nloop, 'at:', ctime()) def main():
print('starting at:', ctime())
threads = [] for i in range(len(loops)):
t = Thread(target=TFun(loop.__name__, loop, (i,loops[i])))
threads.append(t) for i in range(len(loops)):
threads[i].start() for i in range(len(loops)):
threads[i].join() print('all done at:', ctime()) if __name__ == '__main__':
main()
运行结果:
starting at: Mon Dec 19 23:46:31 2016
loop 0 at: Mon Dec 19 23:46:31 2016
loop 1 at: Mon Dec 19 23:46:31 2016
loop 1 at: Mon Dec 19 23:46:33 2016
loop 0 at: Mon Dec 19 23:46:35 2016
all done at: Mon Dec 19 23:46:35 2016
方法三:
派生Thread子类,创建子类实例
from threading import Thread
from time import ctime, sleep loops = [4, 2] class mythread(Thread):
def __init__(self, func, args, name=''):
Thread.__init__(self)
self.name = name
self.func = func
self.args = args
self.name = name def run(self): #注意不是__call__(self)
self.func(*self.args) def loop(nloop, nsec):
print('loop', nloop, 'at:', ctime())
sleep(nsec)
print('loop ', nloop, 'end at:', ctime()) def main():
print('starting at:', ctime())
threads = [] for i in range(len(loops)):
t = mythread(loop,(i,loops[i]))
threads.append(t) for i in range(len(loops)):
threads[i].start() for i in range(len(loops)):
threads[i].join() print('end at:', ctime()) if __name__ == '__main__':
main()
运行结果:
starting at: Tue Dec 20 00:06:00 2016
loop 0 at: Tue Dec 20 00:06:00 2016
loop 1 at: Tue Dec 20 00:06:00 2016
loop 1 end at: Tue Dec 20 00:06:02 2016
loop 0 end at: Tue Dec 20 00:06:04 2016
end at: Tue Dec 20 00:06:04 2016
方法二和方法三可以测试多个函数,其中方法三更加直观。但是方法1更加简单
参考资料:Python核心编程.第四章.Wesley Chun著
【Python@Thread】threading模块的更多相关文章
- python中threading模块详解(一)
python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...
- Python使用Threading模块创建线程
使用Threading模块创建线程,直接从threading.Thread继承,然后重写__init__方法和run方法: #!/usr/bin/python # -*- coding: UTF-8 ...
- 再看python多线程------threading模块
现在把关于多线程的能想到的需要注意的点记录一下: 关于threading模块: 1.关于 传参问题 如果调用的子线程函数需要传参,要在参数后面加一个“,”否则会抛参数异常的错误. 如下: for i ...
- python中threading模块中最重要的Tread类
Tread是threading模块中的重要类之一,可以使用它来创造线程.其具体使用方法是创建一个threading.Tread对象,在它的初始化函数中将需要调用的对象作为初始化参数传入. 具体代码如下 ...
- 学会使用Python的threading模块、掌握并发编程基础
threading模块 Python中提供了threading模块来实现线程并发编程,官方文档如下: 官方文档 添加子线程 实例化Thread类 使用该方式新增子线程任务是比较常见的,也是推荐使用的. ...
- Python之Threading模块
Thread 先引入一个例子: >>> from threading import Thread,currentThread,activeCount >>> > ...
- Python之threading模块的使用
作用:同一个进程空间并发运行多个操作,专业术语简称为:[多线程] 1.任务函数不带参数多线程 #!/usr/bin/env python # -*- coding: utf-8 -*- import ...
- Python(多线程threading模块)
day27 参考:http://www.cnblogs.com/yuanchenqi/articles/5733873.html CPU像一本书,你不阅读的时候,你室友马上阅读,你准备阅读的时候,你室 ...
- python中threading模块中的Join类
join类是threading中用于堵塞当前主线程的类,其作用是阻止全部的线程继续运行,直到被调用的线程执行完毕或者超时.具体代码如下: import threading,time def doWai ...
- Python中threading模块的join函数
Join的作用是阻塞进程直到线程执行完毕.通用的做法是我们启动一批线程,最后join这些线程结束,例如: for i in range(10): t = ThreadTest(i) thread_ar ...
随机推荐
- 递归思路分解(C#)
例子一:求1!+2!+......+X! 思路分解:因为是用递归思想解决问题,也就是方法调用方法.那么肯定的方法是重复利用的.在这道题里,我们要重复利用的也就是求X!和求和 所以我们先把求X!的代码写 ...
- c++ 常见问题之 const
const 默认状态下const对象仅在文件内有效,添加extern关键字可以在多个文件共享 const 引用: 可以把引用绑定到const对象上,对常量的引用不能被用作修改它所绑定的对象 const ...
- weak引用变量是否线程安全
1.在ARC出现之前,Objetive-C的内存管理需要手工执行release&retain操作,这些极大增加了代码的编写难度,同时带来很多的crash. 同时大量的delegate是unr ...
- Front-End(二)——HTML
本文主要对html迭代学习中的要点.冷点简述罗列. html之前也说过,主要为了描述页面的结构和内容,合理使用结构化的标签,<h1>.<div>等,有利于前端开发,也有利于搜索 ...
- 算法系列——huffman编码
哈夫曼编码,旨在对信息实现一种高效的编码,这种编码中任何一个都不是其他编码的前缀码.因此,在实际接收时,一旦匹配,就可以立即解码. 具体算法过程可以参加网上的很多教程. 给出一个自己的实现,一方面加强 ...
- c/c++笔试面试经典函数实现
/* strcpy函数实现 拷贝字符串 */ char* Strcpy(char* dst, char* src) { assert(dst != NULL && src != NUL ...
- java.lang.IllegalArgumentException: View not attached to window manager
公司项目线上bug: java.lang.IllegalArgumentException: View not attached to window manager at android.view.W ...
- strut2配置文件属性介绍
mystruts.xml配置文件属性介绍 1.package标签的中的namespace属性 <package name="default" extends="st ...
- Chrome 插件自定义博客编辑界面
总觉得博客园的编辑器太白了,特别是在晚上,太明亮了刺眼.在后台设置里面找不到任何可以修改UI的地方,考虑用浏览器插件自己改一下.要是做得好,可以给大家一起用. 新建目录 E:/cnblog.js,添加 ...
- Intellij Idea使用频率较高的几个快捷键
自动补全参数定义: Ctrl+Alt+V 运行断点Expression: Alt+F8 选择具体的方法以断点步入:Shift+F7 智能操作: Alt+Enter 打开最近文件:Ctrl+E 打开最近 ...