0
点赞
收藏
分享

微信扫一扫

Python 内置队列 queue快速一览

_鱼与渔_ 2022-04-03 阅读 105
python后端

之前的多线程解决线程安全的时候,学委展示了两篇关于队列的 带你验收一款线程安全的队列 和使用队列改造转账场景线程安全问题

刚好这个库比较简单,不超过500行,挨着多线程,那就顺便把队列这个库。

内置的队列都有哪些?

打开源码,除了开头定义了空队列Empty异常和满队列异常Full异常。

主要提供了两类队列:Queue及其衍生类 vs SimpleQueue

Queue和它的衍生类

  • LifoQueue:先进后出队列(LastInFirstOut Q)
  • PriorityQueue:优先队列
  • Queue:其他队列的父类。(见下图)

屏幕快照 2022-02-02 上午12.12.32.png

之前说过这个Queue为线程安全的队列,同样的LifoQueue和PriorityQueue也是线程安全的。

可以放心的使用它放在多线程场景使用,进行多线程的数据交互。

然后这里稍微展示一下:LifoQueue:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2022/2/2 12:43 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : lifoqdemo.py
# @Project : hello
import queue
import threading
import time

lifoq = queue.LifoQueue(3) # 虎年就设置一个三吧

lifoq.put("一祝各位朋友们新年快乐")
lifoq.put("二祝各位朋友们身体健康")
lifoq.put("三祝各位朋友们虎年大吉")


def more_blessing():
count = 0
while count < 3:
print("wait....")
count += 1
lifoq.put("其他的祝福%s" % count)


def get_from_q():
while not lifoq.empty():
print("%s ㊗️:%s" % (threading.current_thread().name, lifoq.get()))


threading.Thread(target=get_from_q, name="学委给朋友们拜年了").start()
threading.Thread(target=more_blessing, name="送更多的祝福").start()

简单队列

SimpleQueue:基于deque和Semaphore实现的简单队列。

但是它也是一个线程安全的类。

Queue和SimpleQueue两者之间的联系:

先把实现抽离,我们可以看到,Queue这个类,对多个线程交互上提供了更多的原生设计,像join和task_done.

因为Queue是可以设置限额的,所以多了一个full方法。而SimpleQueue是一个没有边界的队列,不需要这个检查。

但是两者底层都是使用了deque这个结构,所以如果我们想要知道线程安全的细节,还需要后面再挖一挖。

为了方便比对,这个是删减版的Queue实现:

class Queue:
'''Create a queue object with a given maximum size.

If maxsize is <= 0, the queue size is infinite.
'''


def __init__(self, maxsize=0):
self.maxsize = maxsize
self._init(maxsize)
self.mutex = threading.Lock()
self.not_empty = threading.Condition(self.mutex)
self.not_full = threading.Condition(self.mutex)
self.all_tasks_done = threading.Condition(self.mutex)
self.unfinished_tasks = 0

def task_done(self):
pass

def join(self):
pass

def qsize(self):
pass

def empty(self):
pass

def full(self):
pass

def put(self, item, block=True, timeout=None):
pass

def get(self, block=True, timeout=None):
pass

def put_nowait(self, item):
pass

def get_nowait(self):
pass

# Override these methods to implement other queue organizations
# (e.g. stack or priority queue).
# These will only be called with appropriate locks held

# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque() #底层还是使用deque这个数据结构

def _qsize(self):
return len(self.queue)

# Put a new item in the queue
def _put(self, item):
self.queue.append(item)

# Get an item from the queue
def _get(self):

为了方便比对,这是删减版本的SimpleQueue:

class SimpleQueue: #_PySimpleQueue


def __init__(self):
self._queue = deque()
self._count = threading.Semaphore(0)

def put(self, item, block=True, timeout=None):
pass

def get(self, block=True, timeout=None):
pass

def put_nowait(self, item):
pass

def get_nowait(self):
pass

def empty(self):
pass

def qsize(self):
pass

更多内容可以查看下面的文章,学委准备了一些实例代码结合场景分享这些内置队列。

Python 内置队列 FIFO vs FILO 队列对比展示

Python 内置优先队列PriorityQueue 高级餐厅用餐场景展示

Python 内置优先队列PriorityQueue 代码解析

Python 内置队列 SimpleQueue 代码解析

喜欢Python的朋友,请关注学委的 Python基础专栏 or Python入门到精通大专栏

举报

相关推荐

0 条评论