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

作者:聪明的狐狸 时间:2023-05-06 02:06:42 

本文实例讲述了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,条件变量,生产者,消费者
0
投稿

猜你喜欢

  • Python 通过爬虫实现GitHub网页的模拟登录的示例代码

    2022-04-27 00:26:39
  • 讲解使用SQL Server升级顾问的详细步骤

    2009-01-04 14:14:00
  • MySQL主从搭建(多主一从)的实现思路与步骤

    2024-01-18 01:14:02
  • 微信公众平台网页授权获取用户基本信息中授权回调域名设置的变动

    2023-11-14 14:01:31
  • SpringSecurity从数据库中获取用户信息进行验证的案例详解

    2024-01-23 17:16:25
  • 让SQL Server数据库自动执行管理任务(一)

    2009-03-20 10:35:00
  • python格式化字符串实例总结

    2023-09-01 04:36:11
  • 关于tensorflow softmax函数用法解析

    2022-10-29 07:42:09
  • 简单了解python反射机制的一些知识

    2022-02-05 15:01:04
  • python实现人脸检测的简单实例

    2023-02-17 16:08:20
  • Python制作一个仿QQ办公版的图形登录界面

    2021-06-23 20:08:49
  • python爬取一组小姐姐图片实例

    2023-08-03 15:05:45
  • 手动实现vue2.0的双向数据绑定原理详解

    2024-04-27 16:09:15
  • MySQL/MariaDB/Percona数据库升级脚本

    2024-01-21 10:01:09
  • oracle学习笔记(三)

    2012-01-05 19:28:42
  • 网页设计十大诀窍

    2007-10-19 13:03:00
  • 带你轻松接触 MySQL中损坏的MyISAM表

    2008-12-19 17:55:00
  • 详解Python中Sync与Async执行速度快慢对比

    2023-02-06 13:26:45
  • Python爬取阿拉丁统计信息过程图解

    2022-04-02 06:23:22
  • Pycharm学习教程(4) Python解释器的相关配置

    2023-12-01 10:11:32
  • asp之家 网络编程 m.aspxhome.com