线程queue
queue is especially useful in threaded programming when information must be exchanged safely between multiple threads.
有三种不同的用法
队列
class queue.Queue(maxsize=0) #队列:先进先出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import queue
q=queue.Queue() q.put('first') q.put('second') q.put('third')
print(q.get()) print(q.get()) print(q.get()) # print(q.get()) 只put三次 但是get第四次就会阻塞了 队列里就三个。怎么可能取到第四个
''' 结果(先进先出): first second third ''' ---------------------------------------------------------- # 队列限制数量 import queue
q2=queue.Queue(3) q2.put('first') q2.put('second') q2.put('third')
# 这样队列满了就阻塞 默认阻塞 q2.put(4) # 等价于 q2.put(4,block=True) # q2.put(4,block=True,timeout=3) # 3秒内没人把值取走 也报错 ---------------------------------------------------------- import queue
q3=queue.Queue(3) q3.put('first') q3.put('second') q3.put('third')
# 这样队列满了就不阻塞 于是报错 q3.put(4,block=False) # 报错 queue.Full # 同样效果的不等待 # q3.put_nowait(4)
-------------------------------------------------------- # 取值的时候设置超时时间 超过就报错 q3.get(block=True,timeout=3)
|
堆栈
class queue.LifoQueue(maxsize=0) #堆栈:last in fisrt out(后进先出)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import queue
q=queue.LifoQueue() q.put('first') q.put('second') q.put('third')
print(q.get()) print(q.get()) print(q.get())
''' 结果(后进先出): third second first '''
|
优先级队列
class queue.PriorityQueue(maxsize=0) #优先级队列:存储数据时可设置优先级的队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import queue
q=queue.PriorityQueue() #put进入一个元组,元组的第一个元素是优先级(通常是数字,也可以是非数字之间的比较),数字越小优先级越高 q.put((20,'a')) q.put((10,'b')) q.put((30,'c'))
print(q.get()) print(q.get()) print(q.get())
''' 结果(数字越小优先级越高,优先级高的优先出队): (10, 'b') (20, 'a') (30, 'c') '''
|