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


Posted in Python onAugust 29, 2018

本文实例讲述了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实现在Windows下安装Django
Oct 17 Python
Django中的forms组件实例详解
Nov 08 Python
在python中画正态分布图像的实例
Jul 08 Python
详细整理python 字符串(str)与列表(list)以及数组(array)之间的转换方法
Aug 30 Python
使用Python制作缩放自如的圣诞老人(圣诞树)
Dec 25 Python
python GUI库图形界面开发之PyQt5控件数据拖曳Drag与Drop详细使用方法与实例
Feb 27 Python
python实现简单学生信息管理系统
Apr 09 Python
解决python使用list()时总是报错的问题
May 05 Python
TensorFlow Autodiff自动微分详解
Jul 06 Python
python mongo 向数据中的数组类型新增数据操作
Dec 05 Python
Python绘制K线图之可视化神器pyecharts的使用
Mar 02 Python
pytorch显存一直变大的解决方案
Apr 08 Python
Python运维自动化之nginx配置文件对比操作示例
Aug 29 #Python
python单例模式实例解析
Aug 28 #Python
Python3.7实现中控考勤机自动连接
Aug 28 #Python
python实现遍历文件夹修改文件后缀
Aug 28 #Python
Python绘制正余弦函数图像的方法
Aug 28 #Python
Python logging模块用法示例
Aug 28 #Python
Python异常处理操作实例详解
Aug 28 #Python
You might like
PHP 5.3新特性命名空间规则解析及高级功能
2010/03/11 PHP
基于curl数据采集之单页面采集函数get_html的使用
2013/04/28 PHP
php设计模式之模板模式实例分析【星际争霸游戏案例】
2020/03/24 PHP
connect中间件session、cookie的使用方法分享
2014/06/17 Javascript
JS选中checkbox后获取table内一行TD所有数据的方法
2015/07/01 Javascript
解决jQuery uploadify在非IE核心浏览器下无法上传
2015/08/05 Javascript
javascript弹出窗口中增加确定取消按钮
2016/06/24 Javascript
AngularJs页面筛选标签小功能
2016/08/01 Javascript
js实现时间轴自动排列效果
2017/03/09 Javascript
AngularJS 中的数据源的循环输出
2017/10/12 Javascript
javascript实现数字配对游戏的实例讲解
2017/12/14 Javascript
JavaScript数组、json对象、eval()函数用法实例分析
2019/02/21 Javascript
Nuxt.js实战和配置详解
2019/08/05 Javascript
webpack是如何实现模块化加载的方法
2019/11/06 Javascript
Python中Collections模块的Counter容器类使用教程
2016/05/31 Python
将python代码和注释分离的方法
2018/04/21 Python
总结Python图形用户界面和游戏开发知识点
2019/05/22 Python
简单了解python的内存管理机制
2019/07/08 Python
python对绑定事件的鼠标、按键的判断实例
2019/07/17 Python
使用python客户端访问impala的操作方式
2020/03/28 Python
详解python如何引用包package
2020/06/07 Python
乐天旅游香港网站:日本饭店预订
2017/11/29 全球购物
美国户外烹饪产品购物网站:Outdoor Cooking
2020/01/10 全球购物
城市规划毕业生求职信
2013/10/10 职场文书
酒店管理毕业生自荐信
2013/10/24 职场文书
求职推荐信
2013/10/28 职场文书
毕业生求职自荐书范文
2014/03/27 职场文书
葬礼司仪主持词
2014/03/31 职场文书
爱心倡议书范文
2014/05/12 职场文书
亚运会口号
2014/06/20 职场文书
助人为乐好少年事迹材料
2014/08/18 职场文书
医生党的群众路线教育实践活动个人对照检查材料
2014/09/23 职场文书
学校党的群众路线教育实践活动总结材料
2014/10/30 职场文书
2014年污水处理厂工作总结
2014/12/19 职场文书
2016高考寄语或鼓励的话语
2015/12/04 职场文书
postgresql如何找到表中重复数据的行并删除
2023/05/08 MySQL