学习版本3.5.2
PriorityQueue类和LifoQueue类继承Queue类然后重写了_init、_qsize、_put、_get这四个类的私有方法
Queue:先进先出队列的同步实现,通过双向列表实现的
# Initialize the queue representation
def _init(self, maxsize):
self.queue = deque()
def _qsize(self):
return len(self.queue)
# Put a new item in the queue
def _put(self, item):
self.queue.append(item)
# Get an item from the queue
def _get(self):
return self.queue.popleft()
PriorityQueue:优先队列的同步实现,通过堆实现
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
heappush(self.queue, item)
def _get(self):
return heappop(self.queue)
LifoQueue:后进先出队列的同步实现,通过list来实现的
def _init(self, maxsize):
self.queue = []
def _qsize(self):
return len(self.queue)
def _put(self, item):
self.queue.append(item)
def _get(self):
return self.queue.pop()
__init__(self, maxsize=0) 初始化队列长度,maxsize为0的时候长度为无限
empty(self) 返回队列是否为空
full(self) 返回队列是否为满
qsize(self) 返回队列的大小(并不可靠)
get(self, block=True, timeout=None) 从队头获取并删除元素,block为true:timeout为None时候,阻塞当前线程直到队列中有可用元素;timeout为非负时候,等了timeout的时间还没有可用元素时候抛出一个Empty异常;block为false:timeout为None时候,队列为空则抛出Empty异常;timeout为非负时候,等待timeout时候后没有可用元素则抛出Empty异常。
get_nowait(self) #return self.get(block=False)
put(self, item, block=True, timeout=None) 在队尾插入一个元素,block为true:timeout为None时候,阻塞当前线程直到队列中有可用位置;timeout为非负时候,等了timeout时间还没有可用位置时候抛出一个Full异常;block为false:timeout为None时候,队列没有位置则抛出Full异常;timeout为非负时候,等待timeout时候后还是没有可用位置则抛出Full异常。
put_nowait(self, item) #return self.put(item, block=False)
join(self) 阻塞当前线程直到队列的任务全部完成了
task_done(self) 通知队列任务的完成情况,当完成时候唤醒被join阻塞的线程
实验代码
#/usr/bin/python3
# -*- utf-8 -*-
#学习版本3.5.2
import threading
import time
import queue
que = queue.Queue(5)
#que = queue.PriorityQueue(5)
#que = queue.LifoQueue(5)
def que_put(item):
que.put(item)
print("put", item)
time.sleep(1)
def que_get():
item = que.get()
print("get", item)
que.task_done()
def que_join():
que.join()
print("task was done")
if __name__ == "__main__":
putthreadlist = []
getthreadlist = []
tlist = [4,5,6,1,2,3]
for i in tlist:
putthreadlist.append(threading.Thread(target=que_put,args=(i,)))
for i in range(6):
getthreadlist.append(threading.Thread(target=que_get))
for tl in putthreadlist:
tl.start()
threading.Thread(target=que_join).start()
for tl in getthreadlist:
tl.start()
print("main")
运行结果
put 4
put 5
put 6
put 1
put 2
get 4
put 3
get 5
get 6
get 1
get 2
get 3
main
task was done
que = queue.PriorityQueue(5)时候的运行结果
put 4
put 5
put 6
put 1
put 2
get 1
put 3
get 2
get 3
get 4
get 5
get 6
main
task was done
que = queue.LifoQueue(5)时候的运行结果
put 4
put 5
put 6
put 1
put 2
get 2
put 3
get 3
get 1
get 6
get 5
get 4
main
task was done