python实现多线程的两种方式
发布时间:2020-05-24 01:57:59 所属栏目:Python 来源:互联网
导读:目前python提供了几种多线程实现方式thread,threading,multithreading,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。
|
目前python 提供了几种多线程实现方式 thread,threading,multithreading,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。 A 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行; 本文介绍两种实现方法。
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()
thclass.py 脚本内容:
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()
以上就是本文的全部内容吗,希望对大家学习python程序设计有所帮助。 (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
