【Python】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 脚本内容
  1. import threading,time
  2. from time import sleep, ctime
  3. def now() :
  4.     return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

  5. def test(nloop, nsec):
  6.     print 'start loop', nloop, 'at:', now()
  7.     sleep(nsec)
  8.     print 'loop', nloop, 'done at:', now()

  9. def main():
  10.     print 'starting at:',now()
  11.     threadpool=[]

  12.     for i in xrange(10):
  13.         th = threading.Thread(target= test,args= (i,2))
  14.         threadpool.append(th)

  15.     for th in threadpool:
  16.         th.start()

  17.     for th in threadpool :
  18.         threading.Thread.join( th )

  19.     print 'all Done at:', now()

  20. if __name__ == '__main__':
  21.         main()
执行结果:


thclass.py 脚本内容:
  1. import threading ,time
  2. from time import sleep, ctime
  3. def now() :
  4.     return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

  5. class myThread (threading.Thread) :
  6.       """docstring for myThread"""
  7.       def __init__(self, nloop, nsec) :
  8.           super(myThread, self).__init__()
  9.           self.nloop = nloop
  10.           self.nsec = nsec

  11.       def run(self):
  12.           print 'start loop', self.nloop, 'at:', ctime()
  13.           sleep(self.nsec)
  14.           print 'loop', self.nloop, 'done at:', ctime()
  15. def main():
  16.      thpool=[]
  17.      print 'starting at:',now()
  18.     
  19.      for i in xrange(10):
  20.          thpool.append(myThread(i,2))
  21.          
  22.      for th in thpool:
  23.          th.start()
  24.    
  25.      for th in thpool:
  26.          th.join()
  27.     
  28.      print 'all Done at:', now()

  29. if __name__ == '__main__':
  30.         main()
执行结果:

 
目录
相关文章
|
8月前
|
安全 Python
|
8月前
|
Python
|
8月前
|
Python
|
3月前
|
Python
Python的多线程
Python的多线程
37 0
|
3月前
|
Python
Python小知识 - Python中的多线程
Python小知识 - Python中的多线程
|
8月前
|
Python
|
8月前
|
Python
|
8月前
|
设计模式 安全 数据库连接
Python | Python学习之多线程详解
Python | Python学习之多线程详解
|
9月前
|
安全 Python
Python3 多线程
Python3 多线程
|
10月前
|
机器学习/深度学习 数据处理 Python
Python应用专题 | 5:Python多进程处理数据
本文介绍如何使用多进程的方式高效处理海量任务数据