python 多线程两种实现方式,Python多线程下的_strptime问题,
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多线程下的_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问题,的更多相关文章
- 【Python】python 多线程两种实现方式
目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更 ...
- Java多线程--两种实现方式
进程概述: 在这之前,有必要了解一下什么是进程? 在一个操作系统中,每个独立的执行的程序都可称为一个进程,也就是"正在运行的程序".如图所示: 线程概述: 如上所述,每个运行的程序 ...
- 快速排序quick_sort(python的两种实现方式)
排序算法有很多,目前最好的是quick_sort:unstable,spatial complexity is nlogN. 快速排序原理 python实现 严蔚敏的 datastruct书中有伪代码 ...
- Java多线程13:读写锁和两种同步方式的对比
读写锁ReentrantReadWriteLock概述 大型网站中很重要的一块内容就是数据的读写,ReentrantLock虽然具有完全互斥排他的效果(即同一时间只有一个线程正在执行lock后面的任务 ...
- 巨蟒python全栈开发数据库前端6:事件onclick的两种绑定方式&&onblur和onfocus事件&&window.onload解释&&小米商城讲解
1.回顾上节内容(JavaScript) 一.JavaScript概述 1.ECMAScript和JavaScript的关系 2.ECMAScript的历史 3.JavaScript是一门前后端都可以 ...
- python常有模块:模块、引入语法、两种执行方式、模块搜索顺序
今天主要讲了以下几点:一.模块三问.定义及分类二.import和from的语法三.文件的两种执行方式及搜索顺序四.内置函数 一.模块.import和from的语法 1.什么是模块 模块是一堆功能函 ...
- python selenium 三种等待方式详解[转]
python selenium 三种等待方式详解 引言: 当你觉得你的定位没有问题,但是却直接报了元素不可见,那你就可以考虑是不是因为程序运行太快或者页面加载太慢造成了元素不可见,那就必须要加等待 ...
- 【转载】pygame安装与两种版本的Python兼容问题
在开始学习游戏编程之前,我们先来安装下pygame和python3.2.5 参考园友: http://www.cnblogs.com/hongten/p/hongten_pygame_install. ...
- python 的几种启动方式
python 的几种启动方式 (1)利用Win的操作系统的:命令行工具 cmd.exe Win + R 调出运行对话框,然后输入cmd,即可调出“命令提示符对话框” 或者 在菜单中店家附件中的命令提 ...
随机推荐
- poj 2431 【优先队列】
poj 2431 Description A group of cows grabbed a truck and ventured on an expedition deep into the jun ...
- jenkins集成错误 标签: 发布 2016-01-10 20:45 747人阅读 评论(21) 收藏
进入ITOO的项目以后,终于要将自己负责的模块在jenkins上面集成发布了.首先自己按照文档要求一步一步的将配置完成,然后构建,不错所料出错了,经过修改,终于构建成功!构建成功以后就没再管了,结果第 ...
- iptables 详细使用
检查状态 先检查是否安装了iptables $ service iptables status 安装iptables $ yum install iptables 升级iptables $ yum u ...
- laravel多表登录出现路由调用错误
public function auth() { // Authentication Routes... $this->get('login', 'Auth\LoginController@sh ...
- 2019-8-31-PowerShell-通过-WMI-获取系统服务
title author date CreateTime categories PowerShell 通过 WMI 获取系统服务 lindexi 2019-08-31 16:55:58 +0800 2 ...
- Python type hints 之 Optional,Union
1,前言 type hint 在pep484加入,我个人觉得这种类似于类型约束的(机制)有点违背了python简单.简洁的初衷,在慢慢向c# java 这种强类型语言看齐的节奏. 不过好在不强制使用, ...
- SpringBoot2集成Activiti6
Activiti是领先的轻量级的,以Java为中心的开源BPMN(Business Process Modeling Notation)引擎,实现了真正的流程自动化.下面介绍如何在SpringBoot ...
- H3C 局域网与OSI参考模型
- 用CSS画平行四边形
<div class="jx">我是一个平行四边形</div> <style> .jx{ //定义div的高度宽度 transform:skew ...
- html5 canvas 3d屏保 源码
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head> <met ...