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
上一篇:单选框和复选框的属性使用


下一篇:Java线程优先级