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中的五种异常处理机制介绍
Sep 02 Python
Python进程间通信用法实例
Jun 04 Python
小议Python中自定义函数的可变参数的使用及注意点
Jun 21 Python
Python中运算符"=="和"is"的详解
Oct 08 Python
Python中取整的几种方法小结
Jan 06 Python
Python编程之黑板上排列组合,你舍得解开吗
Oct 30 Python
Django JWT Token RestfulAPI用户认证详解
Jan 23 Python
Django 对IP访问频率进行限制的例子
Aug 30 Python
python列表推导式入门学习解析
Dec 02 Python
Python通过TensorFLow进行线性模型训练原理与实现方法详解
Jan 15 Python
python json.dumps中文乱码问题解决
Apr 01 Python
keras.utils.to_categorical和one hot格式解析
Jul 02 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定时更新程序设计思路分享
2014/06/10 PHP
ThinkPHP3.2.2的插件控制器功能
2015/03/05 PHP
php获得网站访问统计信息类Compete API用法实例
2015/04/02 PHP
php自动更新版权信息显示的方法
2015/06/19 PHP
php正则表达式验证(邮件地址、Url地址、电话号码、邮政编码)
2016/03/14 PHP
PHP使用mysqli操作MySQL数据库的简单方法
2017/02/04 PHP
一个实用的php验证码类
2017/07/06 PHP
使用JS进行目录上传(相当于批量上传)
2010/12/05 Javascript
js中判断Object、Array、Function等引用类型对象是否相等
2012/08/29 Javascript
js如何获取file控件的完整路径具体实现代码
2013/05/15 Javascript
Jquery原生态实现表格header头随滚动条滚动而滚动
2014/03/18 Javascript
jQuery实现字符串按指定长度加入特定内容的方法
2015/03/11 Javascript
js使用setTimeout实现定时炸弹的方法
2015/04/10 Javascript
JavaScript实现选择框按比例拖拉缩放的方法
2015/08/04 Javascript
JavaScript实现算术平方根算法-代码超简单
2015/09/11 Javascript
js console.log打印对像与数组用法详解
2016/01/21 Javascript
微信小程序(六):列表上拉加载下拉刷新示例
2017/01/13 Javascript
vue实现前进刷新后退不刷新效果
2018/01/26 Javascript
详解vuex状态管理模式
2018/11/01 Javascript
[55:56]NB vs Infamous 2019国际邀请赛淘汰赛 败者组 BO3 第二场 8.22
2019/09/05 DOTA
用Python将动态GIF图片倒放播放的方法
2016/11/02 Python
python中dict字典的查询键值对 遍历 排序 创建 访问 更新 删除基础操作方法
2018/09/13 Python
对python插入数据库和生成插入sql的示例讲解
2018/11/14 Python
matplotlib实现显示伪彩色图像及色度条
2019/12/07 Python
DjangoWeb使用Datatable进行后端分页的实现
2020/05/18 Python
Python bisect模块原理及常见实例
2020/06/17 Python
Python selenium如何打包静态网页并下载
2020/08/12 Python
Banana Republic欧盟:美国都市简约风格的代表品牌
2018/05/09 全球购物
小学英语教师先进事迹
2014/05/28 职场文书
揭牌仪式策划方案
2014/05/28 职场文书
运动会的口号
2014/06/09 职场文书
依法行政工作汇报
2014/10/28 职场文书
初一年级组工作总结
2015/08/12 职场文书
青年文明号创建口号大全
2015/12/25 职场文书
检讨书格式
2019/04/25 职场文书
Sql Server之数据类型详解
2022/02/28 SQL Server