python多线程有几种实现方法
发布时间:2020-12-17 17:08:19 所属栏目:Python 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 ??????? 目前python 提供了几种多线程实现方式 thread,threading,multithreading,其中thread模块比较底层,而threading模块是对thread做了一些包装
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考
??????? 目前python 提供了几种多线程实现方式 thread,threading,multithreading,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。2.7版本之前python对线程的支 持还不够完善,不能利用多核CPU,但是2.7版本的python中已经考虑改进这点,出现了multithreading? 模块。threading模块里面主要是对一些线程的操作对象化,创建Thread的class。
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','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() 第二种是创建一个新的class,将要执行的代码 写到run函数里面。 import threading,time.localtime() ) ) class myThread (threading.Thread) : """docstring for myThread""" def __init__(self,nsec) : super(myThread,self).__init__() self.nloop = nloop self.nsec = nsec def run(self): print 'start loop',self.nloop,ctime() sleep(self.nsec) print 'loop',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() 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |