【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 ...
随机推荐
- grunt--自动化打包工具使用
用grunt搭建自动化的web前端开发环境-完整教程 jQuery在使用grunt,bootstrap在使用grunt,百度UEditor在使用grunt,你没有理由不学.不用! 1. 前言 各位we ...
- D3.js:完整的柱形图
一个完整的柱形图包含三部分:矩形.文字.坐标轴.本章将对前几章的内容进行综合的运用,制作一个实用的柱形图,内容包括:选择集.数据绑定.比例尺.坐标轴等内容. (1) 添加SVG画布 //画布大小 va ...
- 【锋利的Jquery】读书笔记六
ajax优点缺点 json格式的严格 { "people": [ { "firstName": "Brett", "lastNam ...
- 在GNU/Linux下使用Lilypond排版简谱
尽管GNU/Linux并非无所不能,但确实能在很多时候提供免费.开放的解决方案.这两天我想做一个简谱,在网上搜索乐谱排版软件,发现了基于GPL协议的Lilypond软件.只不过Lilypond是用来做 ...
- android 控件ui
公共参数: android:id="@+id/text_view" 给当前控件定义了 一个唯一标识符如:text_view android:layout_width=" ...
- redis配置文件redis.conf的参数说明
打开redis.conf文件: # By default Redis does not run as a daemon. Use 'yes' if you need it. # Note that R ...
- Sonatype Nexus 服务启动失败问题解决
Sonatype Nexus 服务启动失败问题解决 问题前述: 近日在开发机本机安装了 Oracle 数据库快捷版 11g2 之后,重启电脑后发现本机的maven代理服务无法访问. 现象 通过 Win ...
- 敏捷开发(七)- SCRUM评估会议
本文主要是为了检测你对SCRUM 评估会议的了解和使用程度, 通过本文你可以检测一下 1.你们的SCRUM 评估会议的过程和步骤 2.SCRUM 评估的输出结果一.会议目的 1 ...
- 修复ubunut桌面
title: 修复ubunut桌面 tags: 桌面, ubuntu grammar_cjkRuby: true --- ,按下Ctrl+Alt+F2.这会让你进入一个命令行界面而不是默认的用户桌面界 ...
- python字符串及正则表达式[转]
原文链接:http://www.cnblogs.com/guojidong/archive/2012/12/20/2826388.html 字符串: 正则表达式 正则表达式元字符与语法图: 注意事项: ...