您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python实现多线程的两种方式

5b51 2022/1/14 8:19:12 python 字数 4423 阅读 376 来源 www.jb51.cc/python

目前python提供了几种多线程实现方式thread,threading,multithreading,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用。

概述

目前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','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程序设计有所帮助。

总结

以上是编程之家为你收集整理的python实现多线程的两种方式全部内容,希望文章能够帮你解决python实现多线程的两种方式所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶