一个简单的消息队列

目录

原理

实现代码

示例


原理

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

实现代码

首先消息队列需要一个队列,我们用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(".")
相关推荐
昀贝27 分钟前
Maven项目引用本地jar涉及scope和systemPath配置
python·maven·jar
Stuomasi_xiaoxin38 分钟前
服务器重装后如何“复活”旧硬盘上的 Anaconda 环境?—— 一次完整的排错与恢复记录
开发语言·python·github
这里有鱼汤43 分钟前
一招横盘突破选股法,赚钱不靠运气靠图形,靠概率!
后端·python
0wioiw01 小时前
Ubuntu基础(Python虚拟环境和Vue)
linux·python·ubuntu
xiao5kou4chang6kai41 小时前
Python-GEE遥感云大数据分析与可视化(如何建立基于云计算的森林监测预警系统)
python·数据分析·云计算·森林监测·森林管理
presenttttt1 小时前
用Python和OpenCV从零搭建一个完整的双目视觉系统(四)
开发语言·python·opencv·计算机视觉
木头左4 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
quant_19865 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言
失败又激情的man10 小时前
python之requests库解析
开发语言·爬虫·python