python实现多线程的两种方式


Posted in Python onMay 22, 2016

目前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()

 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()

以上就是本文的全部内容吗,希望对大家学习python程序设计有所帮助。

Python 相关文章推荐
Python使用Paramiko模块编写脚本进行远程服务器操作
May 05 Python
python GUI实例学习
Nov 21 Python
今天 平安夜 Python 送你一顶圣诞帽 @微信官方
Dec 25 Python
详解tensorflow实现迁移学习实例
Feb 10 Python
python中pika模块问题的深入探究
Oct 13 Python
Python变量类型知识点总结
Feb 18 Python
Python全局锁中如何合理运用多线程(多进程)
Nov 06 Python
numpy.linalg.eig() 计算矩阵特征向量方式
Nov 29 Python
python创建n行m列数组示例
Dec 02 Python
python中的线程threading.Thread()使用详解
Dec 17 Python
python如何从键盘获取输入实例
Jun 18 Python
使用python库xlsxwriter库来输出各种xlsx文件的示例
Sep 01 Python
python实现简单购物商城
May 21 #Python
python字符串的常用操作方法小结
May 21 #Python
python实现用户登录系统
May 21 #Python
python列表的常用操作方法小结
May 21 #Python
bat和python批量重命名文件的实现代码
May 19 #Python
批处理与python代码混合编程的方法
May 19 #Python
python实现汉诺塔递归算法经典案例
Mar 01 #Python
You might like
php+mysql实现无限级分类 | 树型显示分类关系
2006/11/19 PHP
laravel实现按月或天或小时统计mysql数据的方法
2019/10/09 PHP
ie focus bug 解决方法
2009/09/03 Javascript
基于jquery.Jcrop的头像编辑器
2010/03/01 Javascript
js 走马灯简单实例
2013/11/21 Javascript
js+jquery常用知识点汇总
2015/03/03 Javascript
jQuery使用animate创建动画用法实例
2015/08/07 Javascript
如何消除inline-block属性带来的标签间间隙
2016/03/31 Javascript
jQuery获取attr()与prop()属性值的方法及区别介绍
2016/07/06 Javascript
JS仿百度自动下拉框模糊匹配提示
2016/07/25 Javascript
js实现增加数字显示的环形进度条效果
2017/02/05 Javascript
分享一个精简的vue.js 图片lazyload插件实例
2017/03/13 Javascript
vue实现树形菜单效果
2018/03/19 Javascript
深入浅析Vue中的slots/scoped slots
2018/04/03 Javascript
解决layui表格内文本超出隐藏的问题
2019/09/12 Javascript
layui富文本编辑器前端无法取值的解决方法
2019/09/18 Javascript
Vue的click事件防抖和节流处理详解
2019/11/13 Javascript
详解Nuxt内导航栏的两种实现方式
2020/04/16 Javascript
[14:50]2018DOTA2亚洲邀请赛开幕式
2018/04/03 DOTA
[38:54]完美世界DOTA2联赛PWL S2 Rebirth vs LBZS 第一场 11.28
2020/12/01 DOTA
编程语言Python的发展史
2014/09/26 Python
python中global用法实例分析
2015/04/30 Python
如何利用Fabric自动化你的任务
2016/10/20 Python
python中numpy基础学习及进行数组和矢量计算
2017/02/12 Python
获取Django项目的全部url方法详解
2017/10/26 Python
python GUI库图形界面开发之PyQt5表单布局控件QFormLayout详细使用方法与实例
2020/03/06 Python
Lombok插件安装(IDEA)及配置jar包使用详解
2020/11/04 Python
CSS3实现伪类hover离开时平滑过渡效果示例
2017/08/10 HTML / CSS
韩都衣舍天猫官方旗舰店:天猫女装销售总冠军
2017/10/10 全球购物
Kaufmann Mercantile官网:家居装饰、配件、户外及更多
2018/09/28 全球购物
学生就业推荐信
2013/11/13 职场文书
以幸福为主题的活动方案
2014/08/22 职场文书
委托证明范本
2014/11/25 职场文书
2014年加油站站长工作总结
2014/12/23 职场文书
nginx共享内存的机制详解
2022/03/21 Servers
VW、VH适配移动端的解决方案与常见问题
2023/05/21 HTML / CSS