【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 ...
随机推荐
- call 与 apply的区别
1.方法定义 call方法: 语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]]) 定义:调用一个对象的一个方法,以另一个对象替换当前对象. 说明: call ...
- CSS3效果收集
收集一些 CSS3 效果 1. 闪烁字效果 原效果>>
- ORA-12516 TNS监听程序找不到符合协议堆栈要求的可用处理程序
服务器上某个数据库出现' ORA-12516: TNS: 监听程序找不到符合协议堆栈要求的可用处理程'错误,要解决该问题首先查看一下数据库现有的进程数,是否已经达到参数processes的大小. 使用 ...
- Help improve Android Studio by sending usage statistics to Google
Please press I agree if you want to help make Android Studio better or I don't agree otherwise. more ...
- hdu 5833 Zhu and 772002 异或方程组高斯消元
ccpc网赛卡住的一道题 蓝书上的原题 但是当时没看过蓝书 今天又找出来看看 其实也不是特别懂 但比以前是了解了一点了 主要还是要想到构造异或方程组 异或方程组的消元只需要xor就好搞了 数学真的是硬 ...
- ios开发之简单实现loading动画效果
最近有朋友问我类似微信语音播放的喇叭动画和界面图片加载loading界面是怎样实现的,是不是就是一个gif图片呢!我的回答当然是否定了,当然不排除也有人用gif图片啊!下面我就来罗列三种实现loadi ...
- urllib模块 | Python 2.7.11
官方文档: https://docs.python.org/2/library/urllib.html 某博客对官方文档较全的翻译: http://h2byte.com/post/tech/relat ...
- 凭借5G研究优势,诺基亚将携手菲律宾将其应用于VR/AR领域
目前,很多人都在抱怨网速不行,影响视频的流畅播放,未来这些问题可以通过5G解决.近日,诺基亚和PLDT的全资子公司Smart首次在菲律宾一个"现场"网络演示上实现了5G速度,该网络 ...
- hdu 3410 Passing the Message(单调队列)
题目链接:hdu 3410 Passing the Message 题意: 说那么多,其实就是对于每个a[i],让你找他的从左边(右边)开始找a[j]<a[i]并且a[j]=max(a[j])( ...
- VS发布网站步骤(先在vs上发布网站到新的文件夹,然后挂到iis上面)
VS发布网站步骤(先在vs上发布网站到新的文件夹,然后挂到iis上面) 首先用vs2010打开一个Asp.Net项目, 也可以通过vs菜单->生成->发布网站 选择发布网站的路径 ...