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的作用就是通知所有线程
  1. import threading
  2. import time
  3.  
  4. # 商品
  5. product = None
  6. # 条件变量
  7. con = threading.Condition(threading.Lock())
  8.  
  9. # 生产者方法
  10. def produce():
  11. global product
  12.  
  13. if con.acquire():
  14. while True:
  15. print('我执行了,produce')
  16. if product is None:
  17. product = 'anything'
  18. print('produce...',product)
  19. print('plock=',con)
  20. # 通知消费者,商品已经生产
  21. con.notify()
  22.  
  23. # 等待通知
  24. con.wait()
  25. time.sleep(2)
  26.  
  27. # 消费者方法
  28. def consume():
  29. global product
  30.  
  31. if con.acquire():
  32. while True:
  33. print('我执行了,consume')
  34. if product is not None:
  35. print('consume...',product)
  36. print('clock=',con)
  37. product = None
  38.  
  39. # 通知生产者,商品已经没了
  40. con.notify()
  41.  
  42. # 等待通知
  43. con.wait()
  44. time.sleep(2)
  45.  
  46. t2 = threading.Thread(target=consume)
  47. t2.start()
  48. t1 = threading.Thread(target=produce)
  49. t1.start()

1、生产者消费者模型

  1. import threading
  2. import time
  3.  
  4. condition = threading.Condition()
  5. products = 0
  6.  
  7. class Producer(threading.Thread):
  8. def run(self):
  9. global products
  10. while True:
  11. if condition.acquire():
  12. if products < 10:
  13. products += 1;
  14. print "Producer(%s):deliver one, now products:%s" %(self.name, products)
  15. condition.notify()#不释放锁定,因此需要下面一句
  16. condition.release()
  17. else:
  18. print "Producer(%s):already 10, stop deliver, now products:%s" %(self.name, products)
  19. condition.wait();#自动释放锁定
  20. time.sleep(2)
  21.  
  22. class Consumer(threading.Thread):
  23. def run(self):
  24. global products
  25. while True:
  26. if condition.acquire():
  27. if products > 1:
  28. products -= 1
  29. print "Consumer(%s):consume one, now products:%s" %(self.name, products)
  30. condition.notify()
  31. condition.release()
  32. else:
  33. print "Consumer(%s):only 1, stop consume, products:%s" %(self.name, products)
  34. condition.wait();
  35. time.sleep(2)
  36.  
  37. if __name__ == "__main__":
  38. for p in range(0, 2):
  39. p = Producer()
  40. p.start()
  41.  
  42. for c in range(0, 3):
  43. c = Consumer()
  44. c.start()

2、生产者消费者模型

  1. import threading
  2.  
  3. alist = None
  4. condition = threading.Condition()
  5.  
  6. def doSet():
  7. if condition.acquire():
  8. while alist is None:
  9. condition.wait()
  10. for i in range(len(alist))[::-1]:
  11. alist[i] = 1
  12. condition.release()
  13.  
  14. def doPrint():
  15. if condition.acquire():
  16. while alist is None:
  17. condition.wait()
  18. for i in alist:
  19. print i,
  20. print
  21. condition.release()
  22.  
  23. def doCreate():
  24. global alist
  25. if condition.acquire():
  26. if alist is None:
  27. alist = [0 for i in range(10)]
  28. condition.notifyAll()
  29. condition.release()
  30.  
  31. tset = threading.Thread(target=doSet,name='tset')
  32. tprint = threading.Thread(target=doPrint,name='tprint')
  33. tcreate = threading.Thread(target=doCreate,name='tcreate')
  34. tset.start()
  35. tprint.start()
  36. tcreate.start()

3、生产者消费者模型

  1. import threading
  2.  
  3. def run(n):
  4. con.acquire()
  5. print('我执行了',threading.current_thread().name)
  6. con.wait()
  7. print("run the thread: %s" %n)
  8. con.release()
  9.  
  10. if __name__ == '__main__':
  11.  
  12. con = threading.Condition()
  13. for i in range(10):
  14. t = threading.Thread(target=run, args=(i,))
  15. t.start()
  16.  
  17. while True:
  18. inp = input('>>>')
  19.  
  20. if inp == 'q':
  21. break
  22. con.acquire()
  23. con.notify(int(inp))
  24. 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. JVM(16)之 双亲委派模型

    开发十年,就只剩下这套架构体系了! >>>   在上一篇博文中,我们知道了如何获得二进制的字节流,并根据获得的字节流去装载一个类.同时也了解到类加载器的存在,每个加载器对应着不同的加 ...

  2. ubuntu-12.04.5-desktop-amd64 安装vmwaretools

    百度文库地址:https://wenku.baidu.com/view/7c1cd211a216147917112820.html 注意:一定要把此文档中的vmwaretools 版本号换成你自己下载 ...

  3. linux ---maven的安装和配置

    linux下的maven的安装和配置:本人使用的是apache-maven-3.3.9-bin.tar.gz------安装maven的前提是JDK安装成功:java -version 测试一下--J ...

  4. JSON 简单例子

    代码: json [ { "title" : "a", "num" : 1 }, { "title" : "b ...

  5. HTML5 绘制阴影

    代码: <!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8 ...

  6. css 文字对齐

    // html <div>姓名</div> <div>手机号码</div> <div>账号</div> <div>密 ...

  7. Java对象流与序列化学习

    对象流与序列化 对象流有两个类 ObjectOutputStream:将java对象的基本数据类型和图形写入OutputStream ObjectInputStream:对以前使用ObjectOutp ...

  8. Boyer-Moore

    Boyer-Moore 只做这些失败的匹配,就可以排除掉相应的对齐位置.在BM算法中,模式串P与文本串T的对准位置依然自左向右移动,而在对准位置确是自右向左的逐一比对各个字符串,具体的,在每一轮自右向 ...

  9. php sqrt()函数 语法

    php sqrt()函数 语法 作用:sqrt()函数的作用是对参数进行求平方根 语法:sqrt(X) 参数: 参数 描述 X 进行求平方根的数字 说明:返回将参数X进行开平方后的结果江苏大理石平台 ...

  10. JS中的作用域及闭包

    1.JS中的作用域 在 es6 出现之前JS中只有全局作用域和函数作用域,没有块级作用域,即 JS 在函数体内有自己的作用域,但是如果不是在函数体的话就全部都是全局作用域.比如在 if.for 等有 ...