python 隊列Queue
阿新 • • 發佈:2018-07-18
sna strong 消費 ext reading cmp while other art
基本FIFO隊列:先進先出。
calss Queue.Queue(maxsize=0)
maxsize是個整數,指明了隊列中能存放的數據個數的上限。一旦達到上限,插入會導致阻塞,直到隊列中的數據被消費掉。
#coding:utf-8 import Queue q=Queue.Queue(5) #隊列中只能存放5個數據 for i in range(5): q.put(i) while not q.empty(): print q.get()
LIFO隊列:後進先出
class Queue.LifoQueue(maxsize=0)
#coding:utf-8 import Queue q=Queue.LifoQueue(5) #隊列中只能存放5個數據 for i in range(5): q.put(i) while not q.empty(): print q.get()
結果:
4
3
2
1
0
優先級隊列
class Queue.PriorityQueue(maxsize=0)
import Queue import threading class Job(object): def __init__(self, priority, description): self.priority = priority self.description = description print ‘Job:‘,description return def __cmp__(self, other): return cmp(self.priority, other.priority) q = Queue.PriorityQueue() q.put(Job(3, ‘level 3 job‘)) q.put(Job(10, ‘level 10 job‘)) q.put(Job(1, ‘level 1 job‘)) def process_job(q): while True: next_job = q.get() print ‘for:‘, 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()
常用方法:
Queue.
qsize
()
Queue.
empty
()
Queue.
full
()
Queue.
put
(item, block=True, timeout=None)
Queue.
put_nowait
(item)
Queue.
get
(block=True, timeout=None)
Queue.
get_nowait
()
Queue.
task_done
()
Queue.
join
()
生產者消費者模型
python 隊列Queue