python实现多线程的两种方式
目前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脚本内容
importthreading,time
fromtimeimportsleep,ctime
defnow():
returnstr(time.strftime('%Y-%m-%d%H:%M:%S',time.localtime()))
deftest(nloop,nsec):
print'startloop',nloop,'at:',now()
sleep(nsec)
print'loop',nloop,'doneat:',now()
defmain():
print'startingat:',now()
threadpool=[]
foriinxrange(10):
th=threading.Thread(target=test,args=(i,2))
threadpool.append(th)
forthinthreadpool:
th.start()
forthinthreadpool:
threading.Thread.join(th)
print'allDoneat:',now()
if__name__=='__main__':
main()
thclass.py脚本内容:
importthreading,time
fromtimeimportsleep,ctime
defnow():
returnstr(time.strftime('%Y-%m-%d%H:%M:%S',time.localtime()))
classmyThread(threading.Thread):
"""docstringformyThread"""
def__init__(self,nloop,nsec):
super(myThread,self).__init__()
self.nloop=nloop
self.nsec=nsec
defrun(self):
print'startloop',self.nloop,'at:',ctime()
sleep(self.nsec)
print'loop',self.nloop,'doneat:',ctime()
defmain():
thpool=[]
print'startingat:',now()
foriinxrange(10):
thpool.append(myThread(i,2))
forthinthpool:
th.start()
forthinthpool:
th.join()
print'allDoneat:',now()
if__name__=='__main__':
main()
以上就是本文的全部内容吗,希望对大家学习python程序设计有所帮助。