Python之queue模块的使用
queue模块的作用
queue模块提供了一个适用于多线程编程的先进先出(FIFO)数据结构,可以用来在生产者和 消费者线程之间的安全地传递消息或其他数据。它会为调用者处理锁定
,使多个线程可以安全而容易地处理同一个Queue实例。Queue的大小(其中包含的元素个数)有受限,以限制内存使用的或处理。
1、队列的先进先出取写和读的示例
import queue q = queue.Queue() for i in range(5): q.put(i) while not q.empty(): print(q.get(), end=' ') print()
运行效果
0 1 2 3 4
2、队列的先进后出取写和读的示例
import queue q = queue.LifoQueue() for i in range(5): q.put(i) while not q.empty(): print(q.get(), end=' ') print()
运行效果
4 3 2 1 0
3、设置优先级队列
import functools import queue 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) q.task_done() workers = [ threading.Thread(target=process_job, args=(q,)), threading.Thread(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 Processing job: Mid-level jobProcessing job: Low-level job