python多线程编程----threading模块
来源:互联网 发布:visio网络图标库vss 编辑:程序博客网 时间:2024/06/05 22:10
1、threading 模块中的内容
- Thread: 一个可执行线程对象
- Lock: 原始的Lock对象 与thread模块中一样
- RLock: 允许单个线程多次请求的Lock
- Condition: 线程等待直到条件满足
- Event : 事件发生时,唤醒所有等待进程
- Semaphore:信号量,标识有限资源的个数
- Timer: 定时启动线程
- Barrier: 等待指定的所有的进程都来到
2、daemon threads 守护进程
如果你的主线程准备退出,并且你并不关心子线程是否完成,可以设置daemon,
‘thread.daemon = True’,表示该线程用于等待其子线程
3、Thread 类
类属:name: 线程名; ident:线程id; daemon:标识线程是否是守护线程
类方法:
“init(group=None,target=None,name=None,args=(),kwargs={},verbose=None,daemon=None”) 类构造函数,target是可执行函数
start(): 开始执行
run(): 定义线程功能,一般在子类中实现
join(timeout=None): 挂起直到调用其的线程结束,或等待timeout的时间
getName(): 返回线程名
setName(name): 设置线程名
isAlive/is_alive() : 线程是否还在运行
例子1:
import threadingfrom time import sleep, ctimeloops = [4,2]def loop(nloop, nsec): print 'start loop',nloopdef main(): print 'starting' threads=[] nloops=range(len(loops)) for i in nloops: t = threading.Thread(target=loop,args=(i,loops[i]) threads.append(t) for i in nloops: thread[i].start() # start threads for i in nloops: # wait for all threads[i].join() # threads to finishif __name__ == '__main__': main()
这里的target也可以是可调用的类实例
例子2:
import threadingform time import sleep, ctimeloops=[4,2]class ThreadFunc(object): def __init__(self,func,args,name=''): self.name=name self.func=func self.args=args def __call__(self): self.func(*self.args)def loop(nloop,nsec): print 'start loop',nloopdef main(): print 'starting' threads = [] nloops= range(len(loops)) for i in nloops: # create all threads t = threading.Thread( target=ThreadFunc(loop,(i,loops[i]),loop.__name__)) threads.append(t) for i in nloops: #start all threads threads.append(t) for i in nloops: #wait for completion threads[i].join() print "all done"if __name__='__main__': main()
- python多线程编程----threading模块
- Python 多线程编程threading模块
- Python:使用threading模块实现多线程编程
- python多线程编程(二)--threading模块
- Python:使用threading模块实现多线程编程
- python多线程编程(二)--threading模块
- Python 多线程 Threading模块
- python threading多线程模块
- python多线程-threading模块
- python多线程模块threading
- Python threading多线程编程
- Python:使用threading模块实现多线程编程一[综述]
- Python:使用threading模块实现多线程编程六[可重入锁RLock]
- Python:使用threading模块实现多线程编程一[综述]
- Python:使用threading模块实现多线程编程六[可重入锁RLock]
- [Python module]使用threading模块实现多线程编程一[综述]
- Learning Python(16)--多线程编程(threading,Queue模块)
- python多线程模块threading简例
- 巧克力爱好者匿名顺序图——管理员
- Eclipse的ADT插件提示版本问题的解决办法
- TCP 连接断连问题剖析
- 免安装版Tomcat配置用户登录项目管理界面
- Android Animation学习笔记
- python多线程编程----threading模块
- ALSA声卡驱动中的DAPM详解之六:精髓所在,牵一发而动全身
- 【读书笔记:C++ primer plus 第六版 中文版】第8章 函数探幽
- svn日常维护
- java 免费发送短信实例程序
- 派生类向基类转换的可访问性
- android属性动画详解2
- WebRTC 学习笔记(2)--libjingle 部分 (P2P传输)
- 【ASP.NET】验证控件