一个简单的消息队列

目录

原理

实现代码

示例


原理

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

实现代码

首先消息队列需要一个队列,我们用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(".")
相关推荐
华科云商xiao徐2 分钟前
Python多线程数据爬取程序模版
爬虫·python
大白爱琴21 分钟前
使用python进行图像处理—像素级操作与图像算术(4)
开发语言·图像处理·python
吴声子夜歌21 分钟前
OpenCV——图像基本操作(一)
python·opencv·计算机视觉
zhanghongyi_cpp21 分钟前
美食出处(文件版)
python
工业互联网专业1 小时前
基于django+vue的健身房管理系统-vue
vue.js·python·django·毕业设计·源码·课程设计·健身房管理系统
aischang2 小时前
统信桌面专业版如何使用python开发平台jupyter
开发语言·python·jupyter·统信uos
红鼻子时代2 小时前
Django RBAC项目后端实战 - 03 DRF权限控制实现
后端·python·django·rabc
敲键盘的小夜猫2 小时前
大模型链路调试平台之LangSmith实战指南
python·langchain
狐凄2 小时前
Python实例题:Python计算概率论
开发语言·python·概率论
Y3174292 小时前
python Day46 学习(日志Day15复习)
python·学习·机器学习