首页 技术 正文
技术 2022年11月11日
0 收藏 731 点赞 3,635 浏览 2337 个字

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

执行结果:
python 多线程两种实现方式,Python多线程下的_strptime问题,

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 多线程两种实现方式,Python多线程下的_strptime问题,
 

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模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774