加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python条件变量之生产者与消费者操作实例分析

发布时间:2020-12-17 08:33:19 所属栏目:Python 来源:网络整理
导读:本篇章节讲解python条件变量之生产者与消费者操作。供大家参考研究具体如下: 互斥锁是最简单的线程同步机制,面对复杂线程同步问题,Python还提供了Condition对象。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供

本篇章节讲解python条件变量之生产者与消费者操作。分享给大家供大家参考,具体如下:

互斥锁是最简单的线程同步机制,面对复杂线程同步问题,Python还提供了Condition对象。Condition被称为条件变量,除了提供与Lock类似的acquire和release方法外,还提供了wait和notify方法。线程首先acquire一个条件变量,然后判断一些条件。如果条件不满足则wait;如果条件满足,进行一些处理改变条件后,通过notify方法通知其他线程,其他处于wait状态的线程接到通知后会重新判断条件。不断的重复这一过程,从而解决复杂的同步问题。

可以认为Condition对象维护了一个锁(Lock/RLock)和一个waiting池。线程通过acquire获得Condition对象,当调用wait方法时,线程会释放Condition内部的锁并进入blocked状态,(但实际上不会block当前线程)同时在waiting池中记录这个线程。当调用notify方法时,Condition对象会从waiting池中挑选一个线程,通知其调用acquire方法尝试取到锁。

Condition对象的构造函数可以接受一个Lock/RLock对象作为参数,如果没有指定,则Condition对象会在内部自行创建一个RLock。

线程同步经典问题----生产者与消费者问题可以使用条件变量轻松解决。

import threading
import time
class Producer(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
  def run(self):
    global count
    while True:
      con.acquire()
      if count <20:
        count += 1
        print self.name," Producer product 1,current is %d" %(count)
        con.notify()
      else:
        print self.name,"Producer say box is full"
        con.wait()
      con.release()
      time.sleep(1)
class Consumer(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)
  def run(self):
    global count
    while True:
      con.acquire()
      if count>4:
        count -=4
        print self.name,"Consumer consume 4,current is %d" %(count)
        con.notify()
      else:
        con.wait()
        print self.name," Consumer say box is empty"
      con.release()
      time.sleep(1)
count = 0
con = threading.Condition()
def test():
  for i in range(1):
    a = Consumer()
    a.start()
  for i in range(1):
    b =Producer()
    b.start()
if __name__=='__main__':
  test()

上面的代码假定消费者消费的比较快,输出结果为:

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python进程与线程操作技巧总结》、《Python Socket编程技巧总结》、《Python图片操作技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读