[Python 多线程] Condition (十)
Condition常用于生产者、消费者模型,为了解决生产者消费者速度匹配问题。
构造方法Condition(lock=None),可以传入一个Lock或RLock对象,默认RLock。
方法:
acquire(*args) 获取锁
release() 释放锁
wait(timeout=None) 等待通知或直到发生超时
notify(n=1) 唤醒至多指定个数的等待的线程,没有等待的线程就没有任何操作
notify_all() 唤醒所有等待的线程。wake up
以下例子,不考虑线程安全问题:
例1:
#Condition
import threading,random,logging
logging.basicConfig(level=logging.INFO) class Dispatcher:
def __init__(self):
self.data = 0
self.event = threading.Event() def produce(self):
for i in range(100):
self.event.wait(1) #每1秒生成一条数据
data = random.randint(1,100)
self.data = data def custom(self):
while True:
logging.info(self.data)
self.event.wait(0.5) # 替换为1表示消费者每1秒取一次数据 d = Dispatcher()
p = threading.Thread(target=d.produce)
c = threading.Thread(target=d.custom) c.start()
p.start() 以下结果:
INFO:root:0
INFO:root:0
INFO:root:0
INFO:root:77
INFO:root:64
INFO:root:64
INFO:root:8
INFO:root:8
INFO:root:85
生产者每1秒钟生成一条数据,消费者每0.5秒就来取一次数据。
例2:
#Condition 通知机制,解决重复
import threading,random,logging
logging.basicConfig(level=logging.INFO) class Dispatcher:
def __init__(self):
self.data = 0
self.event = threading.Event()
self.cond = threading.Condition() def produce(self):
for i in range(100):
data = random.randint(1,100)
with self.cond:
self.data = data
self.cond.notify_all() #通知所有waiter
self.event.wait(1) #1秒生产一次数据 def custom(self):
while True:
with self.cond:
self.cond.wait() #无限等待
logging.info(self.data) #消费 self.event.wait(0.5) #0.5秒消费一次数据 d = Dispatcher()
p = threading.Thread(target=d.produce)
c = threading.Thread(target=d.custom) c.start()
p.start() 运行结果:
INFO:root:64
INFO:root:43
INFO:root:11
INFO:root:28
INFO:root:30
INFO:root:33
INFO:root:93
INFO:root:69
INFO:root:4
使用with来管理Condition的上下文(acquire/release),利用Condition通知机制解决消费者获取重复数据。
例3:
#Condition 先生成后消费,1对1
import threading,random,logging
logging.basicConfig(level=logging.INFO,format="%(thread)d %(threadName)s %(message)s") class Dispatcher:
def __init__(self):
self.data = 0
self.event = threading.Event()
self.cond = threading.Condition() def produce(self):
for i in range(100):
data = random.randint(1,100)
logging.info(self.data)
with self.cond:
self.data = data
self.cond.notify(1)
# self.cond.notify_all()
self.event.wait(1) def custom(self):
while True:
with self.cond:
self.cond.wait()
logging.info(self.data) self.event.wait(0.5) d = Dispatcher()
p = threading.Thread(target=d.produce,name='produce')
c = threading.Thread(target=d.custom,name='c')
c1 = threading.Thread(target=d.custom,name='c1')
p.start() e = threading.Event()
e.wait(3) c1.start()
c.start() 运行结果:
7520 produce 0
7520 produce 78
7520 produce 88
7520 produce 14
7520 produce 83
2508 c1 86
7520 produce 86
1136 c 79
7520 produce 79
2508 c1 77
7520 produce 77
1136 c 47
7520 produce 47
2508 c1 76
7520 produce 76
1136 c 69
生产者先生产数据,2个消费者一个一个来消费数据。
例4:
#Condition 1对多,2个2个通知
import threading,random,logging
logging.basicConfig(level=logging.INFO,format="%(thread)d %(threadName)s %(message)s") class Dispatcher:
def __init__(self):
self.data = 0
self.event = threading.Event()
self.cond = threading.Condition() def produce(self):
for i in range(100):
data = random.randint(1,100)
logging.info(self.data)
with self.cond:
self.data = data
self.cond.notify(2)
# self.cond.notify_all()
self.event.wait(1) def custom(self):
while True:
with self.cond:
self.cond.wait()
logging.info(self.data)
# self.event.wait(0.5) d = Dispatcher()
p = threading.Thread(target=d.produce,name='produce') for i in range(5):
threading.Thread(target=d.custom,name='c-{}'.format(i)).start() p.start() 以下结果:
8688 produce 0
10376 c-0 90
7928 c-1 90
8688 produce 90
7640 c-2 61
10748 c-3 61
8688 produce 61
10376 c-0 73
1344 c-4 73
8688 produce 73
7928 c-1 57
7640 c-2 57
8688 produce 57
10748 c-3 71
10376 c-0 71
1对多,2个2个通知来处理数据。
以上例子中,程序本身不是线程安全的,程序逻辑有很多瑕疵,但是可以很好的帮助理解Condition的使用,和生产者消费者模型。
Condition总结:
Condition采用通知机制,常用于生产者消费者模型中,解决生产者消费者速度匹配的问题。
使用方法:
使用Condition,必须先acquire,用完之后要release,因为内部使用了锁,默认使用RLock,最好的方法是使用with上下文管理。
生产者wait,会阻塞等待通知,被激活。
生产者生产好消息,对消费者发通知,可以使用notidy_all() 通知所有消费者或者notify()。
[Python 多线程] Condition (十)的更多相关文章
- [Python 多线程] asyncio (十六)
asyncio 该模块是3.4版本加入的新功能. 先来看一个例子: def a(): for x in range(3): print('a.x', x) def b(): for x in 'abc ...
- Python 多线程 Condition 的使用
Condition Condition(条件变量)通常与一个锁关联.需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例. 可 ...
- python多线程--Condition(条件对象)
Condition class threading.Condition(lock=None 这个类实现条件变量对象.条件变量允许一个或多个线程等待,知道它们被另一个线程唤醒. 如果给出了lock参数而 ...
- [Python 多线程] Concurrent (十五)
concurrent包只有一个模块: concurrent.futures - 启动并行任务 异步并行任务编程模块,提供一个高级的异步可执行的便利接口. futures模块提供了2个池执行器 Thre ...
- 关于Python多线程condition变量的应用
''' 所谓条件变量,即这种机制是在满足了特定的条件后,线程才可以访问相关的数据. 它使用Condition类来完成,由于它也可以像锁机制那样用,所以它也有acquire方法和release方法,而且 ...
- 第十五章、Python多线程之信号量和GIL
目录 第十五章.Python多线程之信号量和GIL 1. 信号量(Semaphore) 2. GIL 说明: 第十五章.Python多线程之信号量和GIL 1. 信号量(Semaphore) 信号量用 ...
- 第十五章、Python多线程同步锁,死锁和递归锁
目录 第十五章.Python多线程同步锁,死锁和递归锁 1. 引子: 2.同步锁 3.死锁 引子: 4.递归锁RLock 原理: 不多说,放代码 总结: 5. 大总结 第十五章.Python多线程同步 ...
- Python 多线程、多进程 (二)之 多线程、同步、通信
Python 多线程.多进程 (一)之 源码执行流程.GIL Python 多线程.多进程 (二)之 多线程.同步.通信 Python 多线程.多进程 (三)之 线程进程对比.多线程 一.python ...
- Python多线程多进程那些事儿看这篇就够了~~
自己以前也写过多线程,发现都是零零碎碎,这篇写写详细点,填一下GIL和Python多线程多进程的坑~ 总结下GIL的坑和python多线程多进程分别应用场景(IO密集.计算密集)以及具体实现的代码模块 ...
随机推荐
- Linux**系统实现log日志自动清理
Linux系统实现log日志自动清理 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: ...
- python 实现websocket
python中websocket需要我们自己实现握手代码,流程是这样:服务端启动websocket服务,并监听.当客户端连接过来时,(需要我们自己实现)服务端就接收客户端的请求数据,拿到请求头,根据请 ...
- 《JavaWeb从入门到改行》过滤器学习笔记
>"; display: block; height: 0; clear: both; visibility: hidden; } #sitemap, #sitemap ul{disp ...
- 关于echarts绘制树图形的注意事项(文字倾斜、数据更新、缓存重绘问题等)
最近项目中使用到echarts的树操作,对其中几点注意事项进行下总结. 效果图: 1.基础配置 options的配置如下: { tooltip: { trigger: 'item', triggerO ...
- LeetCode 531----Lonely Pixel I----两种算法之间性能的比较
Lonely Pixel I 两种算法之间的性能比较 今天参加LeetCode Weekly Contest 22,第二题 "Lonely Pixel I" 问题描述如下: Giv ...
- 如何从只会 C++ 语法的水平到达完成项目编写软件的水平?
原文:https://www.zhihu.com/question/29702729 学习 C++ 有一段时间了,但只是停留在熟悉语法阶段,在看 C++primer,不过感觉这本书比较深奥,不太适合, ...
- 交叉编译 Cross-compiling for Linux
@(134 - Linux) Part 1 交叉编译简介 1.1 What is cross-compiling? 对于没有做过嵌入式编程的人,可能不太理解交叉编译的概念,那么什么是交叉编译?它有什么 ...
- linux下C语言三种get输入方式
第一种:scanf() #include "stdio.h" #include "string.h" int main() { ]; scanf("% ...
- “小小科技女神”与微软DigiGirlz Day的约会
上周五在微软中国上海科技园举行的微软科技女生夏令营终于在一天“忙碌的轻松中”,伴随着师生和工程师们的欢笑结束了. 本次的微软科技女生夏令营一共有来自上海闵行区七宝中学.莘庄中学和闵行中学的共50名高中 ...
- Recursive functions and algorithms
http://en.wikipedia.org/wiki/Recursion_(computer_science)#Recursive_functions_and_algorithms A commo ...