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的web.py框架实现类似Django的ORM查询的教程
May 02 Python
python opencv检测目标颜色的实例讲解
Apr 02 Python
python 删除列表里所有空格项的方法总结
Apr 18 Python
python实现名片管理系统
Nov 29 Python
在python带权重的列表中随机取值的方法
Jan 23 Python
Django框架登录加上验证码校验实现验证功能示例
May 23 Python
在windows下使用python进行串口通讯的方法
Jul 02 Python
python+logging+yaml实现日志分割
Jul 22 Python
Python: 传递列表副本方式
Dec 19 Python
Tensorflow进行多维矩阵的拆分与拼接实例
Feb 07 Python
Python实现我的世界小游戏源代码
Mar 02 Python
Python 第三方库 openpyxl 的安装过程
Dec 24 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
re0第二季蕾姆被制作组打入冷宫!艾米莉亚女主扶正,原因唏嘘
2020/04/02 日漫
关于session在PHP5的配置文件中的详细设置参数说明
2011/04/20 PHP
eAccelerator的安装与使用详解
2013/06/13 PHP
php中实现精确设置session过期时间的方法
2014/07/17 PHP
javascript arguments 传递给函数的隐含参数
2009/08/21 Javascript
javascript中全局对象的parseInt()方法使用介绍
2013/12/19 Javascript
理运用命名空间让js不产生冲突避免全局变量的泛滥
2014/06/15 Javascript
在JavaScript中操作时间之setYear()方法的使用
2015/06/12 Javascript
jQuery获取attr()与prop()属性值的方法及区别介绍
2016/07/06 Javascript
JS验证不重复验证码
2017/02/10 Javascript
解决Vue.js父组件$on无法监听子组件$emit触发事件的问题
2018/09/12 Javascript
解决vue使用vant下拉框van-dropdown-item 绑定title值不变问题
2020/08/05 Javascript
vue如何使用rem适配
2021/02/06 Vue.js
Python中字典(dict)合并的四种方法总结
2017/08/10 Python
python3中的md5加密实例
2018/05/29 Python
Python利用字典破解WIFI密码的方法
2019/02/27 Python
Django使用AJAX调用自己写的API接口的方法
2019/03/06 Python
Python要如何实现列表排序的几种方法
2020/02/21 Python
Pytorch框架实现mnist手写库识别(与tensorflow对比)
2020/07/20 Python
Python为何不支持switch语句原理详解
2020/10/21 Python
如何让PyQt5中QWebEngineView与JavaScript交互
2020/10/21 Python
jupyter notebook远程访问不了的问题解决方法
2021/01/11 Python
html5 CSS过度-webkit-transition使用介绍
2013/07/02 HTML / CSS
波兰品牌内衣及泳装网上商店:Astratex.pl
2017/02/03 全球购物
英国领先的瓷砖专家:Walls and Floors
2018/04/27 全球购物
污水厂厂长岗位职责
2014/01/04 职场文书
软件项目开发计划书
2014/05/01 职场文书
2014办公室年度工作总结
2014/12/09 职场文书
先进工作者主要事迹材料
2015/11/03 职场文书
慰问信(范文3篇)
2019/10/23 职场文书
解决Jupyter-notebook不弹出默认浏览器的问题
2021/03/30 Python
mysql对于模糊查询like的一些汇总
2021/05/09 MySQL
postgresql使用filter进行多维度聚合的解决方法
2021/07/16 PostgreSQL
基于Python实现将列表数据生成折线图
2022/03/23 Python
苹果发布了MagSafe固件更新,可以不外接电源实现最高7.5W充电
2022/04/21 数码科技
浅析JavaScript中的变量提升
2022/06/01 Javascript