search
HomeBackend DevelopmentPython TutorialPython中使用Queue和Condition进行线程同步的方法

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()

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

  :一支穿云箭
西米:千军万马来相见
  :山无棱,天地合,乃敢与君绝!
西米:海可枯,石可烂,激情永不散!
  :紫薇!!!!(此处图片省略)
西米:尔康!!!(此处图片省略)
  :是你
西米:是我
  :有钱吗 借点
西米:滚

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools