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. Codeforces 1110C (思维+数论)

    题面 传送门 分析 这种数据范围比较大的题最好的方法是先暴力打表找规律 通过打表,可以发现规律如下: 定义\(x=2^{log_2a+1}\) (注意,cf官方题解这里写错了,官方题解中定义\(x=2 ...

  2. [暑假集训Day3T3]平板涂色

    同样是搜索经典题. 优化并不多,只需在当前步数已经大于目前答案时剪枝就可以了. 此题重点在于如何判断第k个矩形能不能选. 设矩形i的左上坐标为i(squ[i].upx,squ[i].upy),右下角坐 ...

  3. 65.Longest Increasing Subsequence(最长增长子序列)

    Level:   Medium 题目描述: Given an unsorted array of integers, find the length of longest increasing sub ...

  4. C#设计模式:桥接模式(Bridge Pattern)

    一,桥接模式,直接上代码 using System; using System.Collections.Generic; using System.Linq; using System.Text; u ...

  5. activiti 5.22 表结构解析及清空流程运行测试数据

    1.结构设计 1.1.    逻辑结构设计 Activiti使用到的表都是ACT_开头的. ACT_RE_*: 'RE'表示repository(存储),RepositoryService接口所操作的 ...

  6. 2018-2-13-win10-uwp-简单MasterDetail

    title author date CreateTime categories win10 uwp 简单MasterDetail lindexi 2018-2-13 17:23:3 +0800 201 ...

  7. 【串线篇】spring boot配置文件大全【下】

    一.配置文件占位符 1.1.随机数 ${random.value}.${random.int}.${random.long} ${random.int(10)}.${random.int[1024,6 ...

  8. bzoj5161 最长上升子序列 状压DP(DP 套 DP) + 打表

    题目传送门 https://lydsy.com/JudgeOnline/problem.php?id=5161 题解 回顾一下以前用二分求 LIS 的方法:令 \(f[i]\) 表示长度为 \(i\) ...

  9. Linux自用指令——2019年10月23日

    1.ls ls命令是列出目录内容(List Directory Contents)的意思.运行它就是列出文件夹里的内容,可能是文件也可能是文件夹. ls -a 列出目录所有文件,包含以.开始的隐藏文件 ...

  10. 日常Git使用——2019年12月11日16:19:03

    1.git介绍 1.1 什么是git? 什么是Git? 比如一个项目,两个人同时参与开发,那么就把这个项目放在一个公共的地方,需要的时候都可以去获取,有什么改动,都可以进行提交. 为了做到这一点,就需 ...