首页 > 编程语言 >Python使用Queue对象实现多线程同步小案例

Python使用Queue对象实现多线程同步小案例

时间:2023-06-09 20:08:26浏览次数:36  
标签:queue Producer get Python self Queue put 多线程 Consumer


queue模块的Queue对象实现了多生产者/多消费者队列,尤其适合需要在多个线程之间进行信息交换的场合,实现了多线程编程所需要的所有锁语义。

Queue对象主要实现了put()和get()方法,分别用来往队列尾部追加元素和在队列头部获取并删除元素。这两个方法都允许指定超时时间,其用法分别为put(item, block=True, timeout=None)和get(block=True, timeout=None)

在下面的代码中,自定义了生产者线程类和消费者线程类,生产者生产随机数量个元素并放置到队列中,消费者则从队列中依次获取其中的元素。

from threading import Thread
from time import sleep
from queue import Queue
from random import randrange
class Producer(Thread):
    '''自定义生产者线程类'''
    def __init__(self, threadname):
        Thread.__init__(self,\
                        name=threadname)
        
    def run(self):
        '''线程运行代码'''
        total = randrange(20)
        for i in range(total):
            # 等待随机时间后往队列中放入一个元素
            sleep(randrange(3))
            myQueue.put(i)
            print(self.getName(),\
                  ' put ', i,\
                  ' to queue.')
        # None表示生产者线程结束
        myQueue.put(None)
class Consumer(Thread):
    def __init__(self, threadname):
        Thread.__init__(self,\
                        name=threadname)
        
    def run(self):
        while True:
            sleep(randrange(3))
            item = myQueue.get()
            if item is None:
                break
            print(self.getName(),\
                  ' get ', item,\
                  ' from queue.')
# 创建队列
myQueue = Queue()
# 创建并启动生产者和消费者线程
Producer('Producer').start()
Consumer('Consumer').start()

第一次运行结果:

Producer  put  0  to queue.

Producer  put  1  to queue.

Producer  put  2  to queue.

Producer  put  3  to queue.

Producer  put  4  to queue.

Consumer  get  0  from queue.

Producer  put  5  to queue.

Consumer  get  1  from queue.

Consumer  get  2  from queue.

Producer  put  6  to queue.

Producer  put  7  to queue.

Consumer  get  3  from queue.

Consumer  get  4  from queue.

Consumer  get  5  from queue.

Consumer  get  6  from queue.

Consumer  get  7  from queue.

第二次运行结果:

Producer  put  0  to queue.

Consumer  get  0  from queue.

Producer  put  1  to queue.

Consumer  get  1  from queue.

Producer  put  2  to queue.

Consumer  get  2  from queue.

Producer  put  3  to queue.

Consumer  get  3  from queue.

Producer  put  4  to queue.

Producer  put  5  to queue.

Consumer  get  4  from queue.

Consumer  get  5  from queue.

Producer  put  6  to queue.

Consumer  get  6  from queue.

Producer  put  7  to queue.

Consumer  get  7  from queue.

Producer  put  8  to queue.

Producer  put  9  to queue.

Consumer  get  8  from queue.

Consumer  get  9  from queue.

Producer  put  10  to queue.

Consumer  get  10  from queue.

Producer  put  11  to queue.

Consumer  get  11  from queue.

标签:queue,Producer,get,Python,self,Queue,put,多线程,Consumer
From: https://blog.51cto.com/u_9653244/6450944

相关文章

  • Python统计多个Powerpoint文件中幻灯片总数量
    晚上吃饭时突然想知道自己做了多少页《Python程序设计》系列教材的配套PPT,于是就有了下面的代码,这套PPT综合了《Python程序设计基础》(ISBN:9787302410584)、《Python程序设计(第2版)》(ISBN:9787302436515)和《Python可以这样学》(ISBN:9787302456469)以及将要出版的《Python程序设计开发宝典......
  • Python计算序列中数字最大差值(美团2016校招笔试题)
    题目要求:给定一个包含若干数字的序列A(本文以列表为例),求满足0≤a≤b<n(其中n为序列长度)的A[b]-A[a]的最大值。编程要点:循环结构用法,切片,内置函数enumerate(),列表推导式。参考代码:fromrandomimportrandrangedefmaxDifference(lst):#负无穷大diff=-float('inf')......
  • Python使用Condition对象实现多线程同步
    使用Condition对象可以在某些事件触发后才处理数据或执行特定的功能代码,可以用于不同线程之间的通信或通知,以实现更高级别的同步。在内部实现上,Condition对象总是与某种锁对象相关联。Condition对象除了具有acquire()和release()方法之外,还有wait()、wait_for()、notify()、notify_......
  • 使用Python开发会聊天的智能小机器人
    本文重点演示使用socket实现TCP通信以及字典和集合的用法,客户端发来信息之后,服务端会尽量猜测客户端要表达的真正意思,然后选择合适的内容进行回复。服务端小机器人代码:importsocketfromos.pathimportcommonprefixwords={'howareyou?':'Fine,thankyou.','howo......
  • Python字符串处理小案例
    连续5天30个小时的Python培训圆满结束,明天早上5点半出发赶飞机回烟台,晚上收拾行李的时候突然想起来20年前做过的一个C语言题目:假设有一个字符串,里面有若干字母o。要求如下:从前到后扫描,把每个字符删除并追加至字符串尾部,如果遇到字母o就删除,直至字符串处理结束。本文代码主要演示字......
  • Python版归并排序算法(附Python程序__name__属性用法演示视频)
    importrandomdefmergeSort(seq,reverse=False):#把原列表分成两部分mid=len(seq)//2left,right=seq[:mid],seq[mid:]#根据需要进行递归iflen(left)>1:left=mergeSort(left)iflen(right)>1:right=mergeS......
  • 使用Python读写文本文件内容
    本文主要演示如何读写文本文件的内容,以及上下文管理语句with的用法。使用上下文管理语句with时,即使在操作文件内容时引发异常也能保证文件被正确关闭。#'w'表示写入文件,默认为文本文件#如果文件test1.txt不存在,就创建#如果文件test1.txt已存在,就覆盖withopen('test1.txt','w')......
  • Python+pillow计算椭圆图形几何中心
    本文所用测试图像文件位于当前文件夹的testimages子文件夹中,并且图像以白色为背景。fromPILimportImageimportosdefsearchLeft(width,height,im):#从左向右扫描forwinrange(width):#从下向上扫描forhinrange(height):#获......
  • Python使用RSA+MD5实现数字签名
    数字签名主要有防抵赖和防篡改两种功能:一是能确定消息确实是由发送方签名并发出来的,因为别人假冒不了发送方的签名,二是能确定消息的完整性。作为具体实现,发送报文时,发送方用一个哈希函数(例如MD5、SHA-1、SHA-256、SHA-384或SHA-512)从报文文本中生成报文摘要,然后用自己的私钥(由RSA......
  • Python+tensorflow计算整数阶乘的方法与局限性
    本文代码主要演示tensorflow的基本用法。importtensorflowas#创建变量,保存计算结果start=tf.Variable(1,dtype=tf.int64)#初始化变量的opinit_op=tf.global_variables_initializer()#启用默认图withtf.Session()assess:#初始化变量sess.run(ini......