Python实现多线程的两种方式分析

yipeiwu_com6年前Python基础

本文实例讲述了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 脚本内容

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', nloop, '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()

执行结果:

starting at: 2018-08-29 09:34:16
start loop 0 at: 2018-08-29 09:34:16
start loop 1 at: 2018-08-29 09:34:16
start loop 2 at: 2018-08-29 09:34:16start loop 3 at: 2018-08-29 09:34:16

start loop 4 start loopat:  52018-08-29 09:34:16
at: 2018-08-29 09:34:16
start loop 6 at: start loop2018-08-29 09:34:16
7 at: 2018-08-29 09:34:16
start loop 8 start loopat: 9  2018-08-29 09:34:16at:
 2018-08-29 09:34:16
looploop 1 done at: 2018-08-29 09:34:18
 0 done at: 2018-08-29 09:34:18
loop 3 done at: 2018-08-29 09:34:18
looploop 5 done at: 2018-08-29 09:34:18
 2 done at: 2018-08-29 09:34:18
loop 4 done at: 2018-08-29 09:34:18
looploop 7 done at: 2018-08-29 09:34:18
 6 done at: 2018-08-29 09:34:18
looploop  98  done at:done at:  2018-08-29 09:34:182018-08-29 09:34:18

all Done at: 2018-08-29 09:34:18

第二种 创建继承自Thread的类

thclass.py 脚本内容:

import threading , time
from time import sleep, ctime
def now() :
 return str(time.strftime('%Y-%m-%d %H:%M:%S' , time.localtime()))
class myThread (threading.Thread) :
 """docstring for myThread"""
 def __init__(self, nloop, nsec) :
  super(myThread, self).__init__()
  self.nloop = nloop
  self.nsec = nsec
 def run(self):
  print 'start loop', self.nloop, 'at:', ctime()
  sleep(self.nsec)
  print 'loop', self.nloop, 'done at:', 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()

执行结果:

starting at: 2018-08-29 09:36:02
start loop 0 at: Wed Aug 29 09:36:02 2018
start loop 1 at: Wed Aug 29 09:36:02 2018
start loop 2 at: Wed Aug 29 09:36:02 2018
start loop 3 at: Wed Aug 29 09:36:02 2018
start loop 4 at: Wed Aug 29 09:36:02 2018
 start loop 5 at: Wed Aug 29 09:36:02 2018
start loop 6 at: Wed Aug 29 09:36:02 2018
start loop 7 at: Wed Aug 29 09:36:02 2018
start loop 8 at: Wed Aug 29 09:36:02 2018
start loop 9 at: Wed Aug 29 09:36:02 2018
loop 0 done at: Wed Aug 29 09:36:04 2018
loop 1 done at: Wed Aug 29 09:36:04 2018
looploop  23  done at:done at:  Wed Aug 29 09:36:04 2018Wed Aug 29 09:36:04 2018

loop 4 done at: Wed Aug 29 09:36:04 2018
loop 5 done at: Wed Aug 29 09:36:04 2018
loop 6 done at: Wed Aug 29 09:36:04 2018
looploop loop 8 9 7 done at: done at: done at: Wed Aug 29 09:36:04 2018 Wed Aug 29 09:36:04 2018
Wed Aug 29 09:36:04 2018

all Done at: 2018-08-29 09:36:04

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python+MySQL数据库程序设计入门教程》及《Python常见数据库操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

相关文章

Python中的下划线详解

这篇文章讨论Python中下划线_的使用。跟Python中很多用法类似,下划线_的不同用法绝大部分(不全是)都是一种惯例约定。 一、 单个下划线直接做变量名(_) 主要有三种情...

Python常用的json标准库

当请求 headers 中,添加一个name为 Accept,值为 application/json 的 header(也即“我”(浏览器)接收的是 json 格式的数据),这样,向服务...

利用Python将时间或时间间隔转为ISO 8601格式方法示例

利用Python将时间或时间间隔转为ISO 8601格式方法示例

前言 大家都知道,Python自带的datetime库提供了将datetime转为ISO 8610格式的函数,但是对于时间间隔(inteval)并没有提供转换的函数,下面我们动手写一个。...

Python使用函数默认值实现函数静态变量的方法

本文实例展示了Python使用函数默认值实现函数静态变量的方法,具体方法如下: 一、Python函数默认值 Python函数默认值的使用可以在函数调用时写代码提供方便,很多时候我们只要使...

对PyQt5基本窗口控件 QMainWindow的使用详解

对PyQt5基本窗口控件 QMainWindow的使用详解

QMainWindow基本介绍 QMainWindow主窗口为用户提供了一个应用程序框架,它有自己的布局,可以在布局中添加控件。 窗口类型介绍 PyQt5中,主要使用以下三个类来创建窗...