python多线程有几种实现方法
发布时间:2020-05-25 17:21:22 所属栏目:Python 来源:互联网
导读:python多线程有几种实现方法
|
下面是脚本之家 jb51.cc 通过网络收集整理的代码片段。 脚本之家小编现在分享给大家,也给大家做个参考。 目前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()
以上是脚本之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。 如果觉得脚本之家网站内容还不错,欢迎将脚本之家网站推荐给程序员好友。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
