1 线程queue
1.1 先进先出 Queue
# 看下类Queue的注释
class Queue:
'''Create a queue object with a given maximum size.
If maxsize is <= 0, the queue size is infinite.
'''
import queue
q = queue.Queue(3) # 给定最大值,如果给定值 <= 0,queue是无穷的
q.put([1,2,3])
q.put(1)
q.put(2)
q.put(3) # 超过给定值就会阻塞住,不报错
q.put()有两个参数,
def put(self, item, block=True,timeout=None)
如果block=False,不阻塞,超过给定值直接报错,等于put_nowait,
def put_nowait(self, item)
return self.put(item, block=False)
如果block=True,timeout设置阻塞时间,超过时间报错。
# q.put(4,block=False) # 报错
# raise Full
# q.put_nowait(4)
# raise Full
# q.put(4,block=True,timeout=3) # 如果block 为true,阻塞时间timeout,超时报错
# raise Full
print(q.get())
print(q.get())
print(q.get())
print(q.get()) # 取完再取也会阻塞
q.get()与put()一样,也有两个参数,也有get_nowait
def get(self, block=True, timeout=None)
def get_nowait(self)
return self.get(block=False)
# print(q.get())
# print(q.get())
# print(q.get())
# print(q.get()) # 阻塞
# print(q.get(block= False)) # 报错
# raise Empty
# print(q.get_nowait())
# raise Empty
1.2 后进先出 LifoQueue
'''Variant of Queue that retrieves most recently added entries first.'''
q = queue.LifoQueue(3) # last in first out 后进先出,堆栈
q.put(1)
q.put(2)
q.put(3)
print(q.get())
print(q.get())
print(q.get())
# 3
# 2
# 1
1.3 优先级队列 PriorityQueue
数字越小,优先级越高,通常传入元祖形式,
(优先级编号,数据)
'''Variant of Queue that retrieves open entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
'''
q = queue.PriorityQueue(4) # 优先级
q.put((4, '3'))
q.put((3, 'hello'))
q.put((5, '5'))
q.put((2, 'hello'))
print(q.get())
print(q.get())
print(q.get())
print(q.get())
结果也是元祖形式
(2, 'hello')
(3, 'hello')
(4, '3')
(5, '5')