python3之queue模块

queue模块提供了一个多线程安全的先进先出FIFO(first in first out)的数据结构。

1.基本使用

put()放入元素,get()取出元素。

import queue
q = queue.Queue()
for i in range(5):
    q.put(i)
# 验证队列是否为空
while not q.empty():
    print(q.get(), end=" ")

输出:

0 1 2 3 4 

2.LIFO队列

与FIFO相反,LIFO是后进后出。

import queue
q = queue.LifoQueue()
for i in range(5):
    q.put(i)
# 验证队列是否为空
while not q.empty():
    print(q.get(), end=" ")

结果:

4 3 2 1 0 

3.优先队列

根据元素的特性来决定这些元素的处理顺序。

import queue
import functools
import threading

@functools.total_ordering
class Job:
    def __init__(self, priority, description):
        self.priority = priority
        self.description = description
        print("New job:", description)
        return
    def __eq__(self, other):
        try:
            return self.priority == other.priority
        except AttributeError:
            return NotImplemented
    def __lt__(self, other):
        try:
            return self.priority < other.priority
        except AttributeError:
            return NotImplemented

q = queue.PriorityQueue()
q.put(Job(3, "Mid-level job"))
q.put(Job(10, "Low-level job"))
q.put(Job(1, "Important job"))
def process_job(q):
    while True:
        # 根据优先级别来拿到新的工作,越重要的越先拿到
        next_job = q.get()
        print("processing job:", next_job.description, threading.current_thread().getName())
        q.task_done()
workers = [
    threading.Thread(name="Thread888", target=process_job, args=(q,))
]
for w in workers:
    w.setDaemon(True)
    w.start()
q.join()

显示结果:

New job: Mid-level job
New job: Low-level job
New job: Important job
processing job: Important job Thread888
processing job: Mid-level job Thread888
processing job: Low-level job Thread888

转载于:https://www.cnblogs.com/haoqirui/p/10367350.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值