视频1 视频21 视频41 视频61 视频文章1 视频文章21 视频文章41 视频文章61 推荐1 推荐3 推荐5 推荐7 推荐9 推荐11 推荐13 推荐15 推荐17 推荐19 推荐21 推荐23 推荐25 推荐27 推荐29 推荐31 推荐33 推荐35 推荐37 推荐39 推荐41 推荐43 推荐45 推荐47 推荐49 关键词1 关键词101 关键词201 关键词301 关键词401 关键词501 关键词601 关键词701 关键词801 关键词901 关键词1001 关键词1101 关键词1201 关键词1301 关键词1401 关键词1501 关键词1601 关键词1701 关键词1801 关键词1901 视频扩展1 视频扩展6 视频扩展11 视频扩展16 文章1 文章201 文章401 文章601 文章801 文章1001 资讯1 资讯501 资讯1001 资讯1501 标签1 标签501 标签1001 关键词1 关键词501 关键词1001 关键词1501 专题2001
python实现多线程的方式
2020-11-27 14:26:09 责编:小采
文档

目前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
from time import sleep, ctime
def now() :
 return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
def test(nloop, nsec):
 print 'start loop', nloop, 'at:', now()
sleep(nsec)
 print 'loop', nloop, 'done at:', now()
def main():
 print 'starting at:',now()
 threadpool=[]
for i in xrange(10):
 th = threading.Thread(target= test,args= (i,2))
 threadpool.append(th)
for th in threadpool:
 th.start()
for th in threadpool :
 threading.Thread.join( th )
 print 'all Done at:', now()
if __name__ == '__main__':
 main()

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()

下载本文
显示全文
专题