一个简单的消息队列

目录

原理

实现代码

示例


原理

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

实现代码

首先消息队列需要一个队列,我们用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(".")
相关推荐
可乐鸡翅yeah_2 分钟前
hls.js 内存泄漏实战排查,直播 M3U8 长时间播放异常定位方案
开发语言·javascript·python·django·ecmascript·m3u8·m3u8在线
可乐鸡翅yeah_8 分钟前
第三方接口对接 M3U8 流媒体排坑实战,解决外部服务商流兼容难题
前端·javascript·python·django·html·m3u8·m3u8在线
金融小师妹12 分钟前
多因子智能推演:黄金震荡回升,杰克逊霍尔“沃什首秀”政策如何重塑金价路径的AI预测框架
大数据·人工智能·python·线性回归
阿童木写作14 分钟前
跨马翻译:AI批量图片翻译与视频字幕翻译工具推荐
人工智能·python·音视频
阿kun要赚马内20 分钟前
MCP(Model Context Protocol,模型上下文协议)
人工智能·python
来了就未晚1 小时前
Python基础 学习代码存储与命名规范
开发语言·python·学习
落魄大学生之流水线上谋生计1 小时前
LangGraph 基本用法指南
java·windows·python·langchain
华研前沿标杆游学2 小时前
宇树科技对外开放参访?机器人企业参访体验与行业核心价值解析
python
今天会营业2 小时前
Miniconda安装
python·机器学习
benchmark_cc2 小时前
Python量化实战:如何检测并剔除历史数据中的“闪崩/乌龙指”异常价格点?
开发语言·人工智能·python·量化·quantdash·量化数据源