最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Python 多线程开发的两种常用方式
时间:2016-08-03 编辑:简简单单 来源:一聚教程网
目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。
2.7版本之前python对线程的支持还不够完善,不能利用多核CPU,但是2.7版本的python中已经考虑改进这点,出现了multithreading 模块。threading模块里面主要是对一些线程的操作对象化,创建Thread的class。一般来说,使用线程有两种模式:
A 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;
B 继承Thread类,创建一个新的class,将要执行的代码 写到run函数里面。
本文介绍两种实现方法。
第一种 创建函数并且传入Thread 对象中
t.py 脚本内容
代码如下 | 复制代码 |
import threading , time |
执行结果:
thclass.py 脚本内容:
代码如下 | 复制代码 |
import threading , time from time import sleep , ctime def now ( ) : return str ( time . strftime ( '%Y-%m-%d %H:%M:%S' , time . localtime ( ) ) ) class myThread ( threading . Thread ) : "" "docstring for myThread" "" def __init__ ( self , nloop , nsec ) : super ( myThread , self ) . __init__ ( ) self . nloop = nloop self . nsec = nsec def run ( self ) : print 'start loop' , self . nloop , 'at:' , ctime ( ) sleep ( self . nsec ) print 'loop' , self . nloop , 'done at:' , ctime ( ) def main ( ) : thpool = [ ] print 'starting at:' , now ( ) for i in xrange ( 10 ) : thpool . append ( myThread ( i , 2 ) ) for th in thpool : th . start ( ) for th in thpool : th . join ( ) print 'all Done at:' , now ( ) if __name__ = = '__main__' : main ( ) |
执行结果:
相关文章
- python多进程和多线程哪个最快 06-01
- 浅谈java多线程 join方法以及优先级方法 02-04
- Java多线程实现的两种方式 01-16
- python10多线程下载器的实现例子 10-21
- 举例理解 python 中多线程用法 09-20
- Python 多线程编程的使用详解 08-21