一个简单的消息队列

目录

原理

实现代码

示例


原理

消息队列是一个先进先出栈,每次都处理第一项,处理完了过后会删除这个消息,这是一个简单的消息队列图:

实现代码

首先消息队列需要一个队列,我们用Python里的列表:

python 复制代码
self.queue = []

接着我们要实现把一个消息加入队列和处理消息:

python 复制代码
def push(self, text):
    self.queue.append(text)

def pull(self):
    test = self.queue[0]
    self.queue.pop()
    return test

示例

然后我们来验证一下:

python 复制代码
import time

'''
消息队列的类
'''

mq = MessageQueue()
for i in range(1, 21):
    mq.push(f"[Error {i}] author is not find")
    print(mq.pull(), end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".")

结果:

Error 1 author is not find...

Error 2 author is not find...

Error 3 author is not find...

Error 4 author is not find...

Error 5 author is not find...

Error 6 author is not find...

Error 7 author is not find...

Error 8 author is not find...

Error 9 author is not find...

Error 10 author is not find...

Error 11 author is not find...

Error 12 author is not find...

Error 13 author is not find...

Error 14 author is not find...

Error 15 author is not find...

Error 16 author is not find...

Error 17 author is not find...

Error 18 author is not find...

Error 19 author is not find...

Error 20 author is not find...

Process finished with exit code 0

列表:

完整代码

python 复制代码
import time

class MessageQueue(object):
    def __init__(self):
        self.queue = []

    def push(self, text):
        self.queue.append(text)

    def pull(self):
        test = self.queue[0]
        self.queue.pop()
        return test

mq = MessageQueue()
for i in range(1, 21):
    mq.push(f"[Error {i}] author is not find")
    print(mq.pull(), end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".", end="")
    time.sleep(0.1)
    print(".")
相关推荐
paeamecium1 小时前
【PAT甲级真题】- Rational Sum (20)
数据结构·c++·python·算法·pat考试·pat
爱昏羔7 小时前
下篇:从检索到交互 — 物流RAG问答系统与WebUI全实现
python·langchain·agent
_Jimmy_7 小时前
Agent引用数据库知识过时的增量同步方案
人工智能·python·langchain
min(a,b)9 小时前
学习第 4 天:面向对象与异常处理
python·学习·学习方法
yangshicong11 小时前
第19章:AI安全防护与AI安全
人工智能·python·安全·prompt·ai编程
果汁华11 小时前
Function Calling 与 Python 实战完整指南
开发语言·网络·python
c_lb728811 小时前
2026年不同基础做量化,先找AI能参与的位置
人工智能·python
chenment13 小时前
ComfyUI 自定义节点开发:从零扩展你的图像生成工作流
python·stable diffusion
IT空门:门主13 小时前
Python 基础语法学习路线图
网络·python·学习
互联网中的一颗神经元13 小时前
小白python入门 - 25. SQL 与表设计入门
数据库·python·sql