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中string模块各属性以及函数的用法介绍
May 30 Python
利用Python批量生成任意尺寸的图片
Aug 29 Python
python随机取list中的元素方法
Apr 08 Python
python判断文件是否存在,不存在就创建一个的实例
Feb 18 Python
selenium获取当前页面的url、源码、title的方法
Jun 12 Python
对python3 sort sorted 函数的应用详解
Jun 27 Python
windows中安装Python3.8.0的实现方法
Nov 19 Python
基于python实现对文件进行切分行
Apr 26 Python
浅谈python 调用open()打开文件时路径出错的原因
Jun 05 Python
基于tf.shape(tensor)和tensor.shape()的区别说明
Jun 30 Python
Python threading模块condition原理及运行流程详解
Oct 05 Python
Python基础之进程详解
May 21 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/05/07 PHP
php实现等比例压缩图片
2018/07/26 PHP
jquery ajax abort()的使用方法
2010/10/28 Javascript
extjs tabpanel限制选项卡数量实现思路及代码
2013/04/02 Javascript
Egret引擎开发指南之编译项目
2014/09/03 Javascript
js实时获取并显示当前时间的方法
2015/07/31 Javascript
jQuery 获取跨域XML(RSS)数据的相关总结分析
2016/05/18 Javascript
Bootstrap 源代码分析(未完待续)
2016/08/17 Javascript
Vue2.0 slot分发内容与props验证的方法
2017/12/12 Javascript
JS实现多物体运动的方法详解
2018/01/23 Javascript
Vue 组件传值几种常用方法【总结】
2018/05/28 Javascript
JQuery 实现文件下载的常用方法分析
2019/10/29 jQuery
javascript实现贪吃蛇小练习
2020/07/05 Javascript
[53:52]EG vs VGJ.T 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
[01:05:52]DOTA2-DPC中国联赛 正赛 Ehome vs Aster BO3 第一场 2月2日
2021/03/11 DOTA
使用PYTHON接收多播数据的代码
2012/03/01 Python
Python中利用sorted()函数排序的简单教程
2015/04/27 Python
python实现log日志的示例代码
2018/04/28 Python
pygame游戏之旅 按钮上添加文字的方法
2018/11/21 Python
python最小生成树kruskal与prim算法详解
2019/01/17 Python
python pandas写入excel文件的方法示例
2019/06/25 Python
Python高级property属性用法实例分析
2019/11/19 Python
在python下实现word2vec词向量训练与加载实例
2020/06/09 Python
Python基于yaml文件配置logging日志过程解析
2020/06/23 Python
python连接mysql数据库并读取数据的实现
2020/09/25 Python
Python实现给PDF添加水印的方法
2021/01/25 Python
Expedia马来西亚旅游网站:廉价酒店,度假村和航班预订
2016/07/26 全球购物
自荐信怎么写呢?
2013/12/09 职场文书
法律专业实习鉴定
2013/12/22 职场文书
销售主管的自我评价分享
2014/01/03 职场文书
成绩单公证书
2014/04/10 职场文书
运动会入场口号
2014/06/07 职场文书
销售队伍口号
2014/06/11 职场文书
离婚协议书范本
2015/01/26 职场文书
第一书记观后感
2015/06/08 职场文书
OpenFeign实现远程调用
2022/08/14 Java/Android