Python中使用Queue和Condition进行线程同步的方法


Posted in Python onJanuary 19, 2016

Queue模块保持线程同步
利用Queue对象先进先出的特性,将每个生产者的数据一次存入队列,而每个消费者将依次从队列中取出数据

import threading    # 导入threading模块
import Queue      # 导入Queue模块
class Producer(threading.Thread):# 定义生产者类
  def __init__(self,threadname):
    threading.Thread.__init__(self,name = threadname)
  def run(self):
    global queue  # 声明queue为全局变量
    queue.put(self.getName())  # 调用put方法将线程名添加到队列中
    print self.getName(),'put ',self.getName(),' to queue'
class Consumer(threading.Thread):# 定义消费者类
  def __init__(self,threadname):
    threading.Thread.__init__(self,name = threadname)
  def run(self):
    global queue
    print self.getName(),'get ',queue.get(),'from queue'#调用get方法获取队列中内容
queue = Queue.Queue()  # 生成队列对象
plist = []   # 生成者对象列表
clist = []   # 消费者对象列表
for i in range(10):
  p = Producer('Producer' + str(i))
  plist.append(p)   # 添加到生产者对象列表
for i in range(10):
  c = Consumer('Consumer' + str(i))
  clist.append(c)   # 添加到消费者对象列表
for i in plist:
  i.start()    # 运行生产者线程
  i.join()
for i in clist:
  i.start()    # 运行消费者线程
  i.join()
######运行结果######
>>> Producer0 put Producer0 to queue
Producer1 put Producer1 to queue
Producer2 put Producer2 to queue
Producer3 put Producer3 to queue
Producer4 put Producer4 to queue
Producer5 put Producer5 to queue
Producer6 put Producer6 to queue
Producer7 put Producer7 to queue
Producer8 put Producer8 to queue
Producer9 put Producer9 to queue
Consumer0 get Producer0 from queue
Consumer1 get Producer1 from queue
Consumer2 get Producer2 from queue
Consumer3 get Producer3 from queue
Consumer4 get Producer4 from queue
Consumer5 get Producer5 from queue
Consumer6 get Producer6 from queue
Consumer7 get Producer7 from queue
Consumer8 get Producer8 from queue
Consumer9 get Producer9 from queue

Condition实现复杂的同步
使用Condition对象可以在某些事件触发或者达到特定的条件后才处理数据,Condition除了具有Lock对象的acquire方法和release方法外,
还有wait方法,notify方法,notifyAll方法等用于条件处理。
条件变量保持线程同步:threading.Condition()

  • wait():线程挂起,直到收到一个notify通知才会被唤醒继续运行
  • notify():通知其他线程,那些挂起的线程接到这个通知之后会开始运行
  • notifyAll(): 如果wait状态线程比较多,notifyAll的作用就是通知所有线程(这个一般用得少)
#coding:utf-8

import threading
import time
cond = threading.Condition()
class kongbaige(threading.Thread):
  def __init__(self, cond, diaosiname):
    threading.Thread.__init__(self, name = diaosiname)
    self.cond = cond
      
  def run(self):
    self.cond.acquire() #获取锁
      
    print self.getName() + ':一支穿云箭' #空白哥说的第一句话
    self.cond.notify()          #唤醒其他wait状态的线程(通知西米哥 让他说话)
    #然后进入wait线程挂起状态等待notify通知(等西米哥的回复,接下来俩人就开始扯蛋)
    self.cond.wait()
      
    print self.getName() + ':山无棱,天地合,乃敢与君绝!'
    self.cond.notify()
    self.cond.wait()
      
    print self.getName() + ':紫薇!!!!(此处图片省略)'
    self.cond.notify()
    self.cond.wait()
      
    print self.getName() + ':是你'
    self.cond.notify()
    self.cond.wait()
      
    #这里是空白哥说的最后一段话,接下来就没有对白了
    print self.getName() + ':有钱吗 借点'
    self.cond.notify()       #通知西米哥
    self.cond.release()      #释放锁
      
      
      
class ximige(threading.Thread):
  def __init__(self, cond, diaosiname):
    threading.Thread.__init__(self, name = diaosiname)
    self.cond = cond
      
  def run(self):
    self.cond.acquire()
    self.cond.wait()  #线程挂起(等西米哥的notify通知)
      
    print self.getName() +':千军万马来相见'
    self.cond.notify() #说完话了notify空白哥wait的线程
    self.cond.wait()  #线程挂起等待空白哥的notify通知
      
    print self.getName() + ':海可枯,石可烂,激情永不散!'
    self.cond.notify()
    self.cond.wait()
      
    print self.getName() + ':尔康!!!(此处图片省略)'
    self.cond.notify()
    self.cond.wait()
      
    print self.getName() + ':是我'
    self.cond.notify()
    self.cond.wait()
      
    #这里是最后一段话,后面空白哥没接话了 所以说完就释放锁 结束线程
    print self.getName() + ':滚' 
    self.cond.release()
      
      
kongbai = kongbaige(cond, '  ')
ximi = ximige(cond, '西米')
#尼玛下面这2个启动标志是关键,虽然是空白哥先开的口,但是不能让他先启动,
#因为他先启动的可能直到发完notify通知了,西米哥才开始启动,
#西米哥启动后会一直处于44行的wait状态,因为空白哥已经发完notify通知了进入wait状态了,
#而西米哥没收到
#造成的结果就是2根线程就一直在那挂起,什么都不干,也不扯蛋了
ximi.start()
kongbai.start()

######运行结果######

:一支穿云箭
西米:千军万马来相见
  :山无棱,天地合,乃敢与君绝!
西米:海可枯,石可烂,激情永不散!
  :紫薇!!!!(此处图片省略)
西米:尔康!!!(此处图片省略)
  :是你
西米:是我
  :有钱吗 借点
西米:滚
Python 相关文章推荐
简单谈谈python中的多进程
Nov 06 Python
Python使用progressbar模块实现的显示进度条功能
May 31 Python
python随机在一张图像上截取任意大小图片的方法
Jan 24 Python
利用Python校准本地时间的方法教程
Oct 31 Python
keras model.fit 解决validation_spilt=num 的问题
Jun 19 Python
python和php哪个更适合写爬虫
Jun 22 Python
matplotlib设置颜色、标记、线条,让你的图像更加丰富(推荐)
Sep 25 Python
Python通过Schema实现数据验证方式
Nov 12 Python
python os.listdir()乱码解决方案
Jan 31 Python
python opencv实现图像配准与比较
Feb 09 Python
python 求两个向量的顺时针夹角操作
Mar 04 Python
如何在Python中创建二叉树
Mar 30 Python
简单总结Python中序列与字典的相同和不同之处
Jan 19 #Python
举例讲解如何在Python编程中进行迭代和遍历
Jan 19 #Python
Python的自动化部署模块Fabric的安装及使用指南
Jan 19 #Python
Python编程中time模块的一些关键用法解析
Jan 19 #Python
Python编程中的文件读写及相关的文件对象方法讲解
Jan 19 #Python
Python使用os模块和fileinput模块来操作文件目录
Jan 19 #Python
举例讲解Python面相对象编程中对象的属性与类的方法
Jan 19 #Python
You might like
PHP基于rabbitmq操作类的生产者和消费者功能示例
2018/06/16 PHP
详解在YII2框架中使用UEditor编辑器发布文章
2018/11/02 PHP
javascript 写的一个简单的timer
2009/07/30 Javascript
Javascript 通过json自动生成Dom的代码
2010/04/01 Javascript
javascript中setInterval的用法
2015/07/19 Javascript
JS实现3D图片旋转展示效果代码
2015/09/22 Javascript
AngularJS中的Directive实现延迟加载
2016/01/25 Javascript
AJAX实现瀑布流触发分页与分页触发瀑布流的方法
2016/05/23 Javascript
使用bat打开多个cmd窗口执行gulp、node
2017/02/17 Javascript
Node.js+jade抓取博客所有文章生成静态html文件的实例
2017/09/19 Javascript
echarts饼图扇区添加点击事件的实例
2017/10/16 Javascript
nodejs(officegen)+vue(axios)在客户端导出word文档的方法
2018/07/31 NodeJs
40行代码把Vue3的响应式集成进React做状态管理
2020/05/20 Javascript
Python实现的数据结构与算法之队列详解
2015/04/22 Python
python实现数组插入新元素的方法
2015/05/22 Python
python提取页面内url列表的方法
2015/05/25 Python
Python的SQLalchemy模块连接与操作MySQL的基础示例
2016/07/11 Python
Python配置mysql的教程(推荐)
2017/10/13 Python
python3使用smtplib实现发送邮件功能
2018/05/22 Python
Python中staticmethod和classmethod的作用与区别
2018/10/11 Python
python实现键盘控制鼠标移动
2020/11/27 Python
python绘制地震散点图
2019/06/18 Python
Spark处理数据排序问题如何避免OOM
2020/05/21 Python
HTML5地理定位与第三方工具百度地图的应用
2016/11/17 HTML / CSS
H5 canvas实现贪吃蛇小游戏
2017/07/28 HTML / CSS
浅谈html5之sse服务器发送事件EventSource介绍
2017/08/28 HTML / CSS
联想瑞士官方网站:Lenovo Switzerland
2017/11/19 全球购物
阿联酋手表和配饰购物网站:Rivolishop
2019/11/25 全球购物
介绍一下木马病毒的种类
2015/07/26 面试题
个人自我评价分享
2013/12/20 职场文书
竞聘上岗演讲稿范文
2014/01/10 职场文书
会议欢迎标语
2014/06/30 职场文书
巴黎圣母院读书笔记
2015/06/26 职场文书
2015年国庆节广播稿
2015/08/19 职场文书
Python初学者必备的文件读写指南
2021/06/23 Python
Vue 打包后相对路径的引用问题
2022/06/05 Vue.js