Condition(条件变量)通常与一个锁关联。需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例。

不理解锁的,请看上一条随笔。

Condition():

  • acquire(): 线程锁
  • release(): 释放锁
  • wait(timeout): 线程挂起,直到收到一个notify通知或者超时(可选的,浮点数,单位是秒s)才会被唤醒继续运行。wait()必须在已获得Lock前提下才能调用,否则会触发RuntimeError。
  • notify(n=1): 通知其他线程,那些挂起的线程接到这个通知之后会开始运行,默认是通知一个正等待该condition的线程,最多则唤醒n个等待的线程。notify()必须在已获得Lock前提下才能调用,否则会触发RuntimeError。notify()不会主动释放Lock。
  • notifyAll(): 如果wait状态线程比较多,notifyAll的作用就是通知所有线程
import threading
import time # 商品
product = None
# 条件变量
con = threading.Condition(threading.Lock()) # 生产者方法
def produce():
global product if con.acquire():
while True:
print('我执行了,produce')
if product is None:
product = 'anything'
print('produce...',product)
print('plock=',con)
# 通知消费者,商品已经生产
con.notify() # 等待通知
con.wait()
time.sleep(2) # 消费者方法
def consume():
global product if con.acquire():
while True:
print('我执行了,consume')
if product is not None:
print('consume...',product)
print('clock=',con)
product = None # 通知生产者,商品已经没了
con.notify() # 等待通知
con.wait()
time.sleep(2) t2 = threading.Thread(target=consume)
t2.start()
t1 = threading.Thread(target=produce)
t1.start()

1、生产者消费者模型

import threading
import time condition = threading.Condition()
products = 0 class Producer(threading.Thread):
def run(self):
global products
while True:
if condition.acquire():
if products < 10:
products += 1;
print "Producer(%s):deliver one, now products:%s" %(self.name, products)
condition.notify()#不释放锁定,因此需要下面一句
condition.release()
else:
print "Producer(%s):already 10, stop deliver, now products:%s" %(self.name, products)
condition.wait();#自动释放锁定
time.sleep(2) class Consumer(threading.Thread):
def run(self):
global products
while True:
if condition.acquire():
if products > 1:
products -= 1
print "Consumer(%s):consume one, now products:%s" %(self.name, products)
condition.notify()
condition.release()
else:
print "Consumer(%s):only 1, stop consume, products:%s" %(self.name, products)
condition.wait();
time.sleep(2) if __name__ == "__main__":
for p in range(0, 2):
p = Producer()
p.start() for c in range(0, 3):
c = Consumer()
c.start()

2、生产者消费者模型

import threading

alist = None
condition = threading.Condition() def doSet():
if condition.acquire():
while alist is None:
condition.wait()
for i in range(len(alist))[::-1]:
alist[i] = 1
condition.release() def doPrint():
if condition.acquire():
while alist is None:
condition.wait()
for i in alist:
print i,
print
condition.release() def doCreate():
global alist
if condition.acquire():
if alist is None:
alist = [0 for i in range(10)]
condition.notifyAll()
condition.release() tset = threading.Thread(target=doSet,name='tset')
tprint = threading.Thread(target=doPrint,name='tprint')
tcreate = threading.Thread(target=doCreate,name='tcreate')
tset.start()
tprint.start()
tcreate.start()

3、生产者消费者模型

import threading

def run(n):
con.acquire()
print('我执行了',threading.current_thread().name)
con.wait()
print("run the thread: %s" %n)
con.release() if __name__ == '__main__': con = threading.Condition()
for i in range(10):
t = threading.Thread(target=run, args=(i,))
t.start() while True:
inp = input('>>>') if inp == 'q':
break
con.acquire()
con.notify(int(inp))
con.release()

总结

1、release和wait都有释放锁的作用,不同在于wait后,该子线程就在那里挂起等待,要继续执行,就需要接收到notify或者notifyAll来唤醒线程,而release该线程还能继续执行。

2、notify和notifyAll的区别在于,notify只能唤醒一个wait,而notifyAll能唤起所有wait。

python Condition类(锁)的更多相关文章

  1. Java:多线程,使用同步锁(Lock)时利用Condition类实现线程间通信

    如果程序不使用synchronized关键字来保证同步,而是直接使用Lock对象来保证同步,则系统中不存在隐式的同步监视器,也就不能用wait().notify().notifyAll()方法进行线程 ...

  2. python线程condition条件锁应用实例

    import time import threading # 吃火锅鱼丸 guo = [] suo = threading.Condition() #条件锁 # 生产者负责生产 class Produ ...

  3. 并发编程---线程 ;python中各种锁

    一,概念 在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程 线程顾名思义,就是一条流水线工作的过程,一条流水线必须属于一个车间,一个车间的工作过程是一个进程 --车间负责把资源整合到 ...

  4. python多进程没有锁队列范例

    假设有一些任务要完成.为了完成这项任务,将使用几个过程.所以,将保持两个队列.一个包含任务,另一个包含已完成任务的日志. 然后实例化流程来完成任务.请注意,python队列类已经同步. 这意味着,我们 ...

  5. muduo网络库学习之MutexLock类、MutexLockGuard类、Condition类、CountDownLatch类封装中的知识点

    一.MutexLock 类 class  MutexLock  :  boost::noncopyable 二.MutexLockGuard类 class  MutexLockGuard  :  bo ...

  6. 孤荷凌寒自学python第四十天python 的线程锁RLock

     孤荷凌寒自学python第四十天python的线程锁RLock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 因为研究同时在多线程中读写同一个文本文件引发冲突,所以使用Lock锁尝试同步, ...

  7. 孤荷凌寒自学python第三十九天python 的线程锁Lock

    孤荷凌寒自学python第三十九天python的线程锁Lock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 当多个线程同时操作一个文件等需要同时操作某一对象的情况发生时,很有可能发生冲突, ...

  8. java多线程,多线程加锁以及Condition类的使用

    看了网上非常多的运行代码,很多都是重复的再说一件事,可能对于java老鸟来说,理解java的多线程是非常容易的事情,但是对于我这样的菜鸟来说,这个实在有点难,可能是我太菜了,网上重复的陈述对于我理解这 ...

  9. Python的条件锁与事件共享

    1:事件机制共享队列: 利用消息机制在两个队列中,通过传递消息,实现可以控制的生产者消费者问题要求:readthread读时,writethread不能写:writethread写时,readthre ...

随机推荐

  1. java_第一年_JavaWeb(5)

    HttpServletRequest对象 通过HttpServletRequest对象可获取客户端在访问服务器时,请求的所有信息 获取客户机的信息 getRequestURL:返回客户端发出请求时的完 ...

  2. hive拉链表以及退链例子笔记

    拉链表设计: 在企业中,由于有些流水表每日有几千万条记录,数据仓库保存5年数据的话很容易不堪重负,因此可以使用拉链表的算法来节省存储空间.  例子: -- 用户信息表; 采集当日全量数据存储到 (当日 ...

  3. bfs(最短路径)

    http://poj.org/problem?id=3278 Catch That Cow Time Limit: 2000MS   Memory Limit: 65536K Total Submis ...

  4. BZOJ 3262(Treap+树状数组)

    题面 传送门 分析 分三维考虑 对第一维,直接排序 对第二维和第三维,我们这样考虑 朴素的方法是建k棵Treap,第i棵Treap里存第二维值为k的第三维数值 每次查询一组(a,b,c),只要在1~b ...

  5. LCT题单(自己的做题情况反馈)(转自Flash)

    LCT题单(自己的做题情况反馈)(转自Flash) 随时进Flash Hu的LCT看一发 也可以看一下我自己的风格的板子 开始 维护链信息(LCT上的平衡树操作) [X] 洛谷P3690 [模板]Li ...

  6. hdu4734 F(x)(数位dp)

    题目传送门 F(x) Time Limit: 1000/500 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)Total S ...

  7. python学习第十三天元组创建和操作方法

    有人问,有了列表,为什么还要有元组呢,到底元组是什么,元组是不可变的有序的列表,一旦创建不能改变,那些地方用到元组呢,小编知道可以应用到数据库连接. 1,元组的创建 n1 = () 元组用的是小括号 ...

  8. 快速部署业务类为webapi服务

    接着前一篇博文,将接口快速打包固定请求格式,不需要修改代码,可以自动完成接口调用,实际上就是生成了一个接口的代理类. 那么仅仅是接口请求代理,没有服务端怎么行?所以需要将实现接口的类部署为webapi ...

  9. 使用wkhtmltopdf工具生成pdf

    背景:将前台页面转换成pdf文档保存到服务器 最开始计划使用canvas2pdf在前端进行生成.但是canva2pdf转换的pdf有严重的失真问题,然后决定使用wkhtmltopdf工具进行生成. 思 ...

  10. POJ 3237 树链剖分

    题目链接:http://poj.org/problem?id=3237 题意:给定一棵n个结点n-1条边的树. 每条边都是一个边权. 现在有4种操作 1:CHANGE I V:把(输入的)第i条边的边 ...