python Condition类(锁)
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,
- 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类(锁)的更多相关文章
- Java:多线程,使用同步锁(Lock)时利用Condition类实现线程间通信
如果程序不使用synchronized关键字来保证同步,而是直接使用Lock对象来保证同步,则系统中不存在隐式的同步监视器,也就不能用wait().notify().notifyAll()方法进行线程 ...
- python线程condition条件锁应用实例
import time import threading # 吃火锅鱼丸 guo = [] suo = threading.Condition() #条件锁 # 生产者负责生产 class Produ ...
- 并发编程---线程 ;python中各种锁
一,概念 在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程 线程顾名思义,就是一条流水线工作的过程,一条流水线必须属于一个车间,一个车间的工作过程是一个进程 --车间负责把资源整合到 ...
- python多进程没有锁队列范例
假设有一些任务要完成.为了完成这项任务,将使用几个过程.所以,将保持两个队列.一个包含任务,另一个包含已完成任务的日志. 然后实例化流程来完成任务.请注意,python队列类已经同步. 这意味着,我们 ...
- muduo网络库学习之MutexLock类、MutexLockGuard类、Condition类、CountDownLatch类封装中的知识点
一.MutexLock 类 class MutexLock : boost::noncopyable 二.MutexLockGuard类 class MutexLockGuard : bo ...
- 孤荷凌寒自学python第四十天python 的线程锁RLock
孤荷凌寒自学python第四十天python的线程锁RLock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 因为研究同时在多线程中读写同一个文本文件引发冲突,所以使用Lock锁尝试同步, ...
- 孤荷凌寒自学python第三十九天python 的线程锁Lock
孤荷凌寒自学python第三十九天python的线程锁Lock (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 当多个线程同时操作一个文件等需要同时操作某一对象的情况发生时,很有可能发生冲突, ...
- java多线程,多线程加锁以及Condition类的使用
看了网上非常多的运行代码,很多都是重复的再说一件事,可能对于java老鸟来说,理解java的多线程是非常容易的事情,但是对于我这样的菜鸟来说,这个实在有点难,可能是我太菜了,网上重复的陈述对于我理解这 ...
- Python的条件锁与事件共享
1:事件机制共享队列: 利用消息机制在两个队列中,通过传递消息,实现可以控制的生产者消费者问题要求:readthread读时,writethread不能写:writethread写时,readthre ...
随机推荐
- JVM(16)之 双亲委派模型
开发十年,就只剩下这套架构体系了! >>> 在上一篇博文中,我们知道了如何获得二进制的字节流,并根据获得的字节流去装载一个类.同时也了解到类加载器的存在,每个加载器对应着不同的加 ...
- ubuntu-12.04.5-desktop-amd64 安装vmwaretools
百度文库地址:https://wenku.baidu.com/view/7c1cd211a216147917112820.html 注意:一定要把此文档中的vmwaretools 版本号换成你自己下载 ...
- linux ---maven的安装和配置
linux下的maven的安装和配置:本人使用的是apache-maven-3.3.9-bin.tar.gz------安装maven的前提是JDK安装成功:java -version 测试一下--J ...
- JSON 简单例子
代码: json [ { "title" : "a", "num" : 1 }, { "title" : "b ...
- HTML5 绘制阴影
代码: <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8 ...
- css 文字对齐
// html <div>姓名</div> <div>手机号码</div> <div>账号</div> <div>密 ...
- Java对象流与序列化学习
对象流与序列化 对象流有两个类 ObjectOutputStream:将java对象的基本数据类型和图形写入OutputStream ObjectInputStream:对以前使用ObjectOutp ...
- Boyer-Moore
Boyer-Moore 只做这些失败的匹配,就可以排除掉相应的对齐位置.在BM算法中,模式串P与文本串T的对准位置依然自左向右移动,而在对准位置确是自右向左的逐一比对各个字符串,具体的,在每一轮自右向 ...
- php sqrt()函数 语法
php sqrt()函数 语法 作用:sqrt()函数的作用是对参数进行求平方根 语法:sqrt(X) 参数: 参数 描述 X 进行求平方根的数字 说明:返回将参数X进行开平方后的结果江苏大理石平台 ...
- JS中的作用域及闭包
1.JS中的作用域 在 es6 出现之前JS中只有全局作用域和函数作用域,没有块级作用域,即 JS 在函数体内有自己的作用域,但是如果不是在函数体的话就全部都是全局作用域.比如在 if.for 等有 ...