Python多线程学习笔记
Python中与多线程相关的模块有 thread, threading 和 Queue等,thread 和threading模块允许程序员创建和管理线程。thread模块提供了基本的线程和锁的支持,而threading提供了更高级别,功能更强的线程管理的功能。Queue 模块允许用户创建一个可以用于多个线程之间共享数据的队列数据结构。一般不建议用thread模块。
1.threading模块
threading 模块对象函数 描述
Thread 表示一个线程的执行的对象
Lock 锁原语对象(跟 thread 模块里的锁对象相同)
RLock 可重入锁对象。使单线程可以再次获得已经获得了的锁(递归锁定)。
Condition 条件变量对象能让一个线程停下来,等待其它线程满足了某个“条件”。如,状态的改变或值的改变。
Event 通用的条件变量。多个线程可以等待某个事件的发生,在事件发生后,所有的线程都会被激活。
Semaphore 为等待锁的线程提供一个类似“等候室”的结构
BoundedSemaphore 与 Semaphore 类似,只是它不允许超过初始值
Timer与 Thread 相似,只是,它要等待一段时间后才开始运行。
threading 模块的其他函数
函数 描述
activeCount() 当前活动的线程对象的数量
currentThread() 返回当前线程对象
enumerate() 返回当前活动线程的列表
settrace(func) 为所有线程设置一个跟踪函数
setprofile(func) a为所有线程设置一个 profile 函数
Thread 对象的函数
函数 描述
start() 开始线程的执行
run() 定义线程的功能的函数(一般会被子类重写)
join(timeout=None) 程序挂起,直到线程结束;如果给了 timeout,则最多阻塞 timeout 秒
getName() 返回线程的名字
setName(name) 设置线程的名字
isAlive() 布尔标志,表示这个线程是否还在运行中
isDaemon() 返回线程的 daemon 标志
setDaemon(daemonic) 把线程的 daemon 标志设为 daemonic(一定要在调用 start()函数前调用)
import threading
from time import sleep,ctime
def loop1():
print "loop1 start at",ctime()
sleep(4)
print "loop1 end at",ctime()
def loop2():
print "loop2 start at",ctime()
sleep(6)
print "loop2 end at ",ctime()
t1=threading.Thread(target=loop1)
t2=threading.Thread(target=loop2)
t1.start()
t2.start()
输出结果:

2.通过Lock实现线程同步
#encoding=utf-8
import threading
from time import sleep,ctime
mylock=threading.RLock() # 实例化一个RLock对象,注意L是大写的
left=10
def loop1(tid):
global left
while 1:
mylock.acquire()
if left>0:
sleep(1)
left=left-1
print str(left)+" tickets left i am thread"+str(tid)
mylock.release() t1=threading.Thread(target=loop1,args=(""))
t2=threading.Thread(target=loop1,args=(""))
t3=threading.Thread(target=loop1,args=(""))
t1.start()
t2.start()
t3.start()
3.继承thead.Tread类实现多线程
#encoding=utf-8
import threading
from time import sleep,ctime
mylock=threading.RLock() # 实例化一个RLock对象,注意L是大写的
left=10
class MyThread(threading.Thread):
def __init__(self,tid):
threading.Thread.__init__(self)
self.tid=tid
def run(self):
global left
while 1:
mylock.acquire()
if left>0:
sleep(1)
left=left-1
print str(left)+" tickets left i am thread"+str(self.tid)
mylock.release() t1=MyThread("")
t2=MyThread("")
t3=MyThread("")
t1.start()
t2.start()
t3.start()
4.Queue模块
函数 描述
Queue 模块函数
queue(size) 创建一个大小为 size 的 Queue 对象
Queue 对象函数
qsize() 返回队列的大小(由于在返回的时候,队列可能会被其它线程修改,所以这个值是近似值)
empty() 如果队列为空返回 True,否则返回 False
full() 如果队列已满返回 True,否则返回 False
put(item,block=0) 把 item 放到队列中,如果给了 block(不为 0),函数会一直阻塞到队列中有空间为止
get(block=0) 从队列中取一个对象,如果给了 block(不为 0),函数会一直阻塞到队列中有对象为止
#encoding=utf-8
import threading
import random
from time import sleep,ctime
from Queue import Queue
myQueue=Queue()
class Product(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue=queue
def run(self):
itemID=1
for i in range(10):
sleep(2)
self.queue.put("item"+str(itemID))
print "product item",itemID
itemID=itemID+1
class Consume(threading.Thread):
def __init__(self,queue):
threading.Thread.__init__(self)
self.queue=queue
def run(self):
itemID=1
while 1: sleep(random.random()*5)
if not self.queue.empty():
item=self.queue.get()
print "consume ",item
else:
print "DONE"
break productT=Product(myQueue)
consumeT=Consume(myQueue)
productT.start()
consumeT.start()
5.使用Queue实现多线程数量控制
#encoding=utf-8
__author__ = 'kevinlu1010@qq.com'
import threading
from time import sleep
from Queue import Queue
q=Queue(5) def f(num):
print num
sleep(1)
q.get()
for i in range(10):
q.put(1,block=1)
p=threading.Thread(target=f,args=[i])
p.start()
这里主要应用了Queue put时可以阻塞的特性来实现线程数的控制
6.高级版:利用线程池和map实现多线程
#encoding=utf-8
__author__ = 'kevinlu1010@qq.com'
from time import sleep
from multiprocessing.dummy import Pool as ThreadPool pool =ThreadPool(4) #线程池的大小,总并发数
def f(a):
print 'hello%s'%str(a)
sleep(1) b=pool.map(f,range(10))
# pool.close()
# pool.join()
print 'hello last'
用到了 multiprocessing 里面的 Pool类,实现起来非常方便,而且效率很高。
参考:http://www.oschina.net/translate/python-parallelism-in-one-line
Python多线程学习笔记的更多相关文章
- python多线程学习笔记(超详细)
python threading 多线程 一. Threading简介 首先看下面的没有用Threading的程序 ): s += i time.sleep( ): s += i time. ...
- 【原】Learning Spark (Python版) 学习笔记(三)----工作原理、调优与Spark SQL
周末的任务是更新Learning Spark系列第三篇,以为自己写不完了,但为了改正拖延症,还是得完成给自己定的任务啊 = =.这三章主要讲Spark的运行过程(本地+集群),性能调优以及Spark ...
- java多线程学习笔记——详细
一.线程类 1.新建状态(New):新创建了一个线程对象. 2.就绪状态(Runnable):线程对象创建后,其他线程调用了该对象的start()方法.该状态的线程位于可运行线程池中, ...
- Python Click 学习笔记(转)
原文链接:Python Click 学习笔记 Click 是 Flask 的团队 pallets 开发的优秀开源项目,它为命令行工具的开发封装了大量方法,使开发者只需要专注于功能实现.恰好我最近在开发 ...
- JAVA多线程学习笔记(1)
JAVA多线程学习笔记(1) 由于笔者使用markdown格式书写,后续copy到blog可能存在格式不美观的问题,本文的.mk文件已经上传到个人的github,会进行同步更新.github传送门 一 ...
- 0003.5-20180422-自动化第四章-python基础学习笔记--脚本
0003.5-20180422-自动化第四章-python基础学习笔记--脚本 1-shopping """ v = [ {"name": " ...
- Python Flask学习笔记之模板
Python Flask学习笔记之模板 Jinja2模板引擎 默认情况下,Flask在程序文件夹中的templates子文件夹中寻找模板.Flask提供的render_template函数把Jinja ...
- Python Flask学习笔记之Hello World
Python Flask学习笔记之Hello World 安装virtualenv,配置Flask开发环境 virtualenv 虚拟环境是Python解释器的一个私有副本,在这个环境中可以安装私有包 ...
- 多线程学习笔记九之ThreadLocal
目录 多线程学习笔记九之ThreadLocal 简介 类结构 源码分析 ThreadLocalMap set(T value) get() remove() 为什么ThreadLocalMap的键是W ...
随机推荐
- java_Hashtable实例
package ming; import java.util.Hashtable; class D { int count; public D(int count) { this.count = co ...
- 可视化swing界面编辑--转载
原文地址:http://279234058.iteye.com/blog/2200122 今天发现了一个WindowBuilder插件,功能好强大,啊哈哈,从此告别手动编辑swing界面代码,直接像V ...
- [COCOS2DX]第一个开源项目的部署和运行<win32版本>
1.无法加载项目: 1.1 按照之前的方法创建一个名为FirstDemo的项目,并将下载到的源代码包全部拷贝到FirstDemo中 1.2 点击demo.sln启动项目: 修改属性: 2.无法打开“g ...
- multithread synchronization use mutex and semaphore
#include <malloc.h> #include <pthread.h> #include <semaphore.h> struct job { /* Li ...
- 浅析PAC,教你动手修改你的PAC文件及user-rule文件实现自动代理
Shadowsocks作为现在一种很流行的穿墙工具,以其轻量级.速度感人等优点深受广大网友热捧.与VP_N相比,他就像一把锋利的”瑞士军刀”,不用受制于“系统全局代理”模式的困扰,控制更加便捷,基于S ...
- svn学习总结
安装svn subversion服务参考博客http://huihai.iteye.com/blog/1985238 一:svn版本管理的作用 a:备份程序 项目开发过程中,防止不可控因素造成的资 ...
- eclipse引用头文件报错问题-解决方法
最近在做一个U-BOOT相关的项目,经过几天的折腾最终放弃使用VIM和一堆附加插件.最终的出的结论是对于中大型工程项目还是要启用一些专业的IDE比较稳妥,尽管VIM提供的各种插件累加在一起足以实现专业 ...
- CSS表格固定列宽
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...
- 关于RSS
RSS(简易信息聚合)是一种消息来源格式规范,用以聚合经常发布更新数据的网站,例如博客文章.新闻.音频或视频的网摘.RSS文件(或称做摘要.网络摘要.或频更新,提供到频道)包含了全文或是节录的文字,再 ...
- 如何使用gcc编译器
开始... 首先,我们应该知道如何调用编译器.实际上,这很简单.我们将从那个著名的第一个C程序开始. #include <stdio.h> int main() { printf(&quo ...