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的几种开发工具介绍
Mar 07 Python
python的常见命令注入威胁
Feb 18 Python
跟老齐学Python之不要红头文件(1)
Sep 28 Python
使用python实现knn算法
Dec 20 Python
利用Hyperic调用Python实现进程守护
Jan 02 Python
python2.7无法使用pip的解决方法(安装easy_install)
Apr 03 Python
一个简单的python爬虫程序 爬取豆瓣热度Top100以内的电影信息
Apr 17 Python
使用Python对微信好友进行数据分析
Jun 27 Python
Python使用Pandas对csv文件进行数据处理的方法
Aug 01 Python
解决python web项目意外关闭,但占用端口的问题
Dec 17 Python
python使用隐式循环快速求和的实现示例
Sep 11 Python
Pycharm Git 设置方法
Sep 15 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
世界第一个无线广播电台 KDKA
2021/03/01 无线电
深思 PHP 数组遍历的差异(array_diff 的实现)
2008/03/23 PHP
二招解决php乱码问题
2012/03/25 PHP
PHPStrom中实用的功能和快捷键大全
2015/09/23 PHP
js 格式化时间日期函数小结
2010/03/20 Javascript
Javascript 设计模式(二) 闭包
2010/05/26 Javascript
通过JavaScript使Div居中并随网页大小改变而改变
2013/06/24 Javascript
关于Javascript作用域链的八点总结
2013/12/06 Javascript
使用JS画图之点、线、面
2015/01/12 Javascript
JS实现的数组全排列输出算法
2015/03/19 Javascript
JS动态改变表格边框宽度的方法
2015/03/31 Javascript
JavaScript基于setTimeout实现计数的方法
2015/05/08 Javascript
jQuery实现灰蓝风格标准二级下拉菜单效果代码
2015/08/31 Javascript
AngularJS动态生成div的ID源码解析
2016/08/29 Javascript
vue 添加vux的代码讲解
2017/11/30 Javascript
优化Vue项目编译文件大小的方法步骤
2019/05/27 Javascript
Weex开发之WEEX-EROS开发踩坑(小结)
2019/10/16 Javascript
vue路由权限校验功能的实现代码
2020/06/07 Javascript
Python中使用haystack实现django全文检索搜索引擎功能
2017/08/26 Python
python交易记录链的实现过程详解
2019/07/03 Python
python数据类型之间怎么转换技巧分享
2019/08/20 Python
Python socket 套接字实现通信详解
2019/08/27 Python
python 异步async库的使用说明
2020/05/04 Python
Python正则表达式如何匹配中文
2020/05/27 Python
详解python程序中的多任务
2020/09/16 Python
魔幻般冒泡背景的CSS3按钮动画
2016/02/27 HTML / CSS
中国双语服务优势的在线购票及活动平台:247tickets
2018/10/26 全球购物
JAVA中的关键字有什么特点
2014/03/07 面试题
阅兵口号
2014/06/19 职场文书
水利水电专业自荐信
2014/07/08 职场文书
教师批评与自我批评材料
2014/10/16 职场文书
学生喝酒检讨书500字
2014/11/02 职场文书
后进生评语大全
2015/01/04 职场文书
拾金不昧感谢信范文
2015/01/21 职场文书
2016元旦文艺汇演主持词(开场白+结束语)
2015/12/03 职场文书
《将心比心》教学反思
2016/02/23 职场文书