一个简单的消息队列

目录

原理

实现代码

示例


原理

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

实现代码

首先消息队列需要一个队列,我们用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(".")
相关推荐
xiaoh_717 分钟前
解决视频处理中的 HEVC 解码错误:Could not find ref with POC xxx【已解决】
python·ffmpeg·音视频
明月与玄武1 小时前
Python编程的真谛:超越语法,理解编程本质
python·编程语言
CodeCraft Studio1 小时前
Excel处理控件Aspose.Cells教程:使用 Python 在 Excel 中进行数据验
开发语言·python·excel
拾忆-eleven1 小时前
C语言实战:用Pygame打造高难度水果消消乐游戏
c语言·python·pygame
旦莫2 小时前
Python 教程:我们可以给 Python 文件起中文名吗?
开发语言·python
豌豆花下猫2 小时前
Python 潮流周刊#99:如何在生产环境中运行 Python?(摘要)
后端·python·ai
小杨4042 小时前
python入门系列二十(peewee)
人工智能·python·pycharm
弧襪2 小时前
FlaskRestfulAPI接口的初步认识
python·flaskrestfulapi
船长@Quant2 小时前
文档构建:Sphinx全面使用指南 — 进阶篇
python·markdown·sphinx·文档构建
cloudy4912 小时前
强化学习:历史基金净产值,学习最大化长期收益
python·强化学习