随笔 - 37, 文章 - 0, 评论 - 0, 阅读 - 30228
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Python Queue队列

Posted on   善恶美丑  阅读(2048)  评论(0编辑  收藏  举报
queue is especially useful in threaded programming when information must be exchanged safely between multiple threads
queue在使用多进程之间交换安全信息的时候特别有用
class queue.Queue(maxsize=0) #先入先出
class queue.LifoQueue(maxsize=0) #last in fisrt out 
class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列 优先级最小最先取出
exception queue.Empty 正常情况下当队列为空则阻塞,如果设置了get_nowaait则会报该异常
Exception raised when non-blocking get() (or get_nowait()) is called on a Queue object which is empty.
exception queue.Full 当设置了put_nowait,队列满时报异常

Exception raised when non-blocking put() (or put_nowait()) is called on a Queue object which is full.

Queue.qsize() 查看队列大小
Queue.empty() #return True if empty   队列为空返回True
Queue.full() # return True if full 
Queue.put(itemblock=Truetimeout=None) 上传到队列 正常当Q满了 在put就阻塞 如果timeout为True 则等待多少秒后直接抛异常
Queue.put_nowait(item)# 队列满直接抛异常
Queue.get(block=Truetimeout=None) #上传到队列,队列空了阻塞
Queue.get_nowait() 队列没数据直接抛异常
Queue.task_done() # q.task_done() 在完成一项工作之后,q.task_done() 函数向任务已经完成的队列发送一个信号. 
Queue.join(实际上意味着等到队列为空,再执行别的操作
复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import queue
class Foo(object):
    def __init__(self,n):
        self.n = n

#q =  queue.Queue(maxsize=30)
#q =  queue.LifoQueue(maxsize=30)
q =  queue.PriorityQueue(maxsize=30)
q.put((2,[1,2,3]))
#q.put(Foo(1))
q.put((10,1))
q.put((3,1))
q.put((5,30))
q.task_done()
q.join()
print(q.get())
print(q.get())
print(q.get())
print(q.get())
复制代码

生产者消费者模型

复制代码
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading,queue
import time

def consumer(n):
    while True:
        print("\033[32;1mconsumer [%s]\033[0m get task:  %s" % (n,q.get()))
        time.sleep(1)
        q.task_done()#每get一次包子,像其他进程告知队列信息
def producer(n):
    count = 1
    while True:
        #time.sleep(1)
        #if q.qsize() <3:
        print("prodcer [%s] produced a new task : %s" %(n,count))
        q.put(count)
        count +=1
        q.join() #queue is emtpy # 等到队列为空在继续往下执行
        print("all taks has been cosumed by consumers...")

q = queue.Queue()
c1 = threading.Thread(target=consumer,args=[1,])
c2 = threading.Thread(target=consumer,args=[2,])
c3 = threading.Thread(target=consumer,args=[3,])
p = threading.Thread(target=producer,args=["XiaoYu",])
p2 = threading.Thread(target=producer,args=["LiuYao",])
c1.start()
c2.start()
c3.start()
p.start()
p2.start()
复制代码

 

编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示