python 多线程两种实现方式

原创 Linux操作系统 作者:杨奇龙 时间:2014-06-08 20:24:26  44021  0
目前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 脚本内容

  1. import threading,time
  2. from time import sleep, ctime
  3. def now() :
  4. return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
  5. def test(nloop, nsec):
  6. print 'start loop', nloop, 'at:', now()
  7. sleep(nsec)
  8. print 'loop', nloop, 'done at:', now()
  9. def main():
  10. print 'starting at:',now()
  11. threadpool=[]
  12. for i in xrange(10):
  13. th = threading.Thread(target= test,args= (i,2))
  14. threadpool.append(th)
  15. for th in threadpool:
  16. th.start()
  17. for th in threadpool :
  18. threading.Thread.join( th )
  19. print 'all Done at:', now()
  20. if __name__ == '__main__':
  21. main()

执行结果:

thclass.py 脚本内容:

  1. import threading ,time
  2. from time import sleep, ctime
  3. def now() :
  4. return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )
  5. class myThread (threading.Thread) :
  6. """docstring for myThread"""
  7. def __init__(self, nloop, nsec) :
  8. super(myThread, self).__init__()
  9. self.nloop = nloop
  10. self.nsec = nsec
  11. def run(self):
  12. print 'start loop', self.nloop, 'at:', ctime()
  13. sleep(self.nsec)
  14. print 'loop', self.nloop, 'done at:', ctime()
  15. def main():
  16. thpool=[]
  17. print 'starting at:',now()
  18. for i in xrange(10):
  19. thpool.append(myThread(i,2))
  20. for th in thpool:
  21. th.start()
  22. for th in thpool:
  23. th.join()
  24. print 'all Done at:', now()
  25. if __name__ == '__main__':
  26. main()

执行结果:

 

Python多线程下的_strptime问题

由于Python的datetime和time中的_strptime方法不支持多线程,运行时会报错:

import datetime
import thread
import time

def f():
    datetime.datetime.strptime("20100101","%Y%m%d")

for _ in xrange(3):
    thread.start_new_thread(f, ())
time.sleep(3)

Unhandled exception in thread started by <function f at 0x2b52c24e66e0>
Traceback (most recent call last):
  File "test.py", line 7, in f
    datetime.datetime.strptime("20100101","%Y%m%d")
AttributeErrorUnhandled exception in thread started by <function f at 0x2b52c24e66e0>:
Traceback (most recent call last):
  File "test.py", line 7, in f
_strptime
    datetime.datetime.strptime("20100101","%Y%m%d")
AttributeError: _strptime

参考 http://bugs.python.org/issue7980

在源文件中可以fix这个bug,不过对于用户来说,还是在使用的时候加锁吧。。

c = threading.RLock()
def f():
    with c:
        datetime.datetime.strptime("20100101","%Y%m%d")

python 多线程两种实现方式,Python多线程下的_strptime问题,的更多相关文章

  1. 【Python】python 多线程两种实现方式

    目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更 ...

  2. Java多线程--两种实现方式

    进程概述: 在这之前,有必要了解一下什么是进程? 在一个操作系统中,每个独立的执行的程序都可称为一个进程,也就是"正在运行的程序".如图所示: 线程概述: 如上所述,每个运行的程序 ...

  3. 快速排序quick_sort(python的两种实现方式)

    排序算法有很多,目前最好的是quick_sort:unstable,spatial complexity is nlogN. 快速排序原理 python实现 严蔚敏的 datastruct书中有伪代码 ...

  4. Java多线程13:读写锁和两种同步方式的对比

    读写锁ReentrantReadWriteLock概述 大型网站中很重要的一块内容就是数据的读写,ReentrantLock虽然具有完全互斥排他的效果(即同一时间只有一个线程正在执行lock后面的任务 ...

  5. 巨蟒python全栈开发数据库前端6:事件onclick的两种绑定方式&&onblur和onfocus事件&&window.onload解释&&小米商城讲解

    1.回顾上节内容(JavaScript) 一.JavaScript概述 1.ECMAScript和JavaScript的关系 2.ECMAScript的历史 3.JavaScript是一门前后端都可以 ...

  6. python常有模块:模块、引入语法、两种执行方式、模块搜索顺序

    今天主要讲了以下几点:一.模块三问.定义及分类二.import和from的语法三.文件的两种执行方式及搜索顺序四.内置函数 一.模块.import和from的语法 1.什么是模块   模块是一堆功能函 ...

  7. python selenium 三种等待方式详解[转]

    python selenium 三种等待方式详解   引言: 当你觉得你的定位没有问题,但是却直接报了元素不可见,那你就可以考虑是不是因为程序运行太快或者页面加载太慢造成了元素不可见,那就必须要加等待 ...

  8. 【转载】pygame安装与两种版本的Python兼容问题

    在开始学习游戏编程之前,我们先来安装下pygame和python3.2.5 参考园友: http://www.cnblogs.com/hongten/p/hongten_pygame_install. ...

  9. python 的几种启动方式

    python 的几种启动方式 (1)利用Win的操作系统的:命令行工具 cmd.exe Win + R  调出运行对话框,然后输入cmd,即可调出“命令提示符对话框” 或者 在菜单中店家附件中的命令提 ...

随机推荐

  1. Hdu 1800 字符串hash

    题目链接 题意: 给出n(n<=3000)个字符串(长度<30,数字组成,肯能存在前导0), 问该序列最少可以分成多少个单调序列.可以转化成求相同字符串的个数的最大值 附上代码: /*** ...

  2. poj3469 最小割

    最大流之后S集合与T集合不在相连,即s不能到达T中的点. 对于同一个模块,Ai,Bi,Ai与源点相连,Bi与汇点相连.不同CPU间消耗的模块,相连. 由于最后模块只能在一个CPU中运行,所以要么与源点 ...

  3. 洛谷2375 BZOJ 3670动物园题解

    题目链接 洛谷链接 我们发现题目要我们求的num[i]东西本质上其实是 求有多少以i结尾的非前缀且能与前缀匹配的字符串,而且要求字符串长度小于(i/2) 我们先不考虑字符串长度的限制,看所有以i结尾的 ...

  4. SDWebImage源码解析之SDWebImageManager的注解

    http://www.cocoachina.com/ios/20150612/12118.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 ...

  5. @CSP模拟2019.10.16 - T3@ 垃圾分类

    目录 @description@ @solution@ @accepted code@ @details@ @description@ 为了保护环境,p6pou建设了一个垃圾分类器. 垃圾分类器是一个 ...

  6. @总结 - 2@ 位运算卷积/子集卷积 —— FWT/FMT

    目录 @0 - 参考资料@ @1 - 异或卷积概念及性质@ @2 - 快速沃尔什正变换(异或)@ @3 - 快速沃尔什逆变换(异或)@ @4 - 与卷积.或卷积@ @5 - 参考代码实现@ @6 - ...

  7. [***]HZOJ 超级树

    DeepinC超详细题解 考试时想出是dp了,因为显然第i级超级树和第i+1级超级树是有联系的(然而我并不能推出来),这dp的状态鬼才想的出来……个人理解,dp的实质就是从小的状态向大的状态转移,从而 ...

  8. 如何把thinkphp 的url改为.html

    ThinkPHP支持伪静态URL设置,可以通过设置URL_HTML_SUFFIX参数随意在URL的最后增加你想要的静态后缀,而不会影响当前操作的正常执行.例如,我们设置'URL_HTML_SUFFIX ...

  9. Android Studio(三):设置Android Studio编码

    Android Studio相关博客: Android Studio(一):介绍.安装.配置 Android Studio(二):快捷键设置.插件安装 Android Studio(三):设置Andr ...

  10. Ext--Layout(布局)

    EXT中的布局,常用的有border.column.fit.form.tabel这几种. Fit布局,子元素将自动填满整个父容器(对元素设置宽度无效),如果容器组件中有多个子元素,则只会显示第一个子元 ...