线程queue

一 线程queue

queue is especially useful in threaded programming when information must be exchanged safely between multiple threads.

有三种不同的用法

class queue.Queue(maxsize=0) #队列:先进先出

from threading import Thread
import queue

q = queue.Queue(3)   # 先进先出(队列)
q.put("first")
q.put(2)
q.put("third")
q.put(4, block=True, timeout=3)    # block = True 队列堵塞,timeout时间后抛异常

print(q.get())
print(q.get())
print(q.get())
# print(q.get(block=False))   #等同于q.get_nowait()
print(q.get(block=True, timeout=3))   # timeout时间后不再等,报错
结果(先进先出): 

first
2
third

 

class queue.LifoQueue(maxsize=0) #堆栈:last in fisrt out

q = queue.LifoQueue(3)   # 后进先出(堆栈)

q.put("first")
q.put(2)
q.put("third")

print(q.get())
print(q.get())
print(q.get())
结果(后进先出):

third
2
first

class queue.PriorityQueue(maxsize=0) #优先级队列:存储数据时可设置优先级的队列

import queue
import queue

q = queue.PriorityQueue(3)    # 优先级队列(数字越小优先级越高)

q.put(("10", "one"))
q.put(("40", "three"))
q.put(("30", "two"))

print(q.get())
print(q.get())
print(q.get())
结果(数字越小优先级越高,优先级高的优先出队): 

('10', 'one')
('30', 'two')
('40', 'three')

 
posted @ 2018-12-17 20:10  混世妖精  阅读(124)  评论(0编辑  收藏  举报