2019独角兽企业重金招聘Python工程师标准>>>
5、双向队列(deque)
一个线程安全的双向队列
class deque(object):"""deque([iterable[, maxlen]]) --> deque objectBuild an ordered collection with optimized access from its endpoints."""def append(self, *args, **kwargs): # real signature unknown""" Add an element to the right side of the deque. """passdef appendleft(self, *args, **kwargs): # real signature unknown""" Add an element to the left side of the deque. """passdef clear(self, *args, **kwargs): # real signature unknown""" Remove all elements from the deque. """passdef count(self, value): # real signature unknown; restored from __doc__""" D.count(value) -> integer -- return number of occurrences of value """return 0def extend(self, *args, **kwargs): # real signature unknown""" Extend the right side of the deque with elements from the iterable """passdef extendleft(self, *args, **kwargs): # real signature unknown""" Extend the left side of the deque with elements from the iterable """passdef pop(self, *args, **kwargs): # real signature unknown""" Remove and return the rightmost element. """passdef popleft(self, *args, **kwargs): # real signature unknown""" Remove and return the leftmost element. """passdef remove(self, value): # real signature unknown; restored from __doc__""" D.remove(value) -- remove first occurrence of value. """passdef reverse(self): # real signature unknown; restored from __doc__""" D.reverse() -- reverse *IN PLACE* """passdef rotate(self, *args, **kwargs): # real signature unknown""" Rotate the deque n steps to the right (default n&#61;1). If n is negative, rotates left. """passdef __copy__(self, *args, **kwargs): # real signature unknown""" Return a shallow copy of a deque. """passdef __delitem__(self, y): # real signature unknown; restored from __doc__""" x.__delitem__(y) <&#61;&#61;> del x[y] """passdef __eq__(self, y): # real signature unknown; restored from __doc__""" x.__eq__(y) <&#61;&#61;> x&#61;&#61;y """passdef __getattribute__(self, name): # real signature unknown; restored from __doc__""" x.__getattribute__(&#39;name&#39;) <&#61;&#61;> x.name """passdef __getitem__(self, y): # real signature unknown; restored from __doc__""" x.__getitem__(y) <&#61;&#61;> x[y] """passdef __ge__(self, y): # real signature unknown; restored from __doc__""" x.__ge__(y) <&#61;&#61;> x>&#61;y """passdef __gt__(self, y): # real signature unknown; restored from __doc__""" x.__gt__(y) <&#61;&#61;> x>y """passdef __iadd__(self, y): # real signature unknown; restored from __doc__""" x.__iadd__(y) <&#61;&#61;> x&#43;&#61;y """passdef __init__(self, iterable&#61;(), maxlen&#61;None): # known case of _collections.deque.__init__"""deque([iterable[, maxlen]]) --> deque objectBuild an ordered collection with optimized access from its endpoints.# (copied from class doc)"""passdef __iter__(self): # real signature unknown; restored from __doc__""" x.__iter__() <&#61;&#61;> iter(x) """passdef __len__(self): # real signature unknown; restored from __doc__""" x.__len__() <&#61;&#61;> len(x) """passdef __le__(self, y): # real signature unknown; restored from __doc__""" x.__le__(y) <&#61;&#61;> x<&#61;y """passdef __lt__(self, y): # real signature unknown; restored from __doc__""" x.__lt__(y) <&#61;&#61;> x
既然有双向队列&#xff0c;也有单项队列&#xff08;先进先出 FIFO &#xff09;
class Queue:"""Create a queue object with a given maximum size.If maxsize is <&#61; 0, the queue size is infinite."""def __init__(self, maxsize&#61;0):self.maxsize &#61; maxsizeself._init(maxsize)self.mutex &#61; _threading.Lock()self.not_empty &#61; _threading.Condition(self.mutex)self.not_full &#61; _threading.Condition(self.mutex)self.all_tasks_done &#61; _threading.Condition(self.mutex)self.unfinished_tasks &#61; 0def task_done(self):self.all_tasks_done.acquire()try:unfinished &#61; self.unfinished_tasks - 1if unfinished <&#61; 0:if unfinished < 0:raise ValueError(&#39;task_done() called too many times&#39;)self.all_tasks_done.notify_all()self.unfinished_tasks &#61; unfinishedfinally:self.all_tasks_done.release()def join(self):self.all_tasks_done.acquire()try:while self.unfinished_tasks:self.all_tasks_done.wait()finally:self.all_tasks_done.release()def qsize(self):"""Return the approximate size of the queue (not reliable!)."""self.mutex.acquire()n &#61; self._qsize()self.mutex.release()return ndef empty(self):"""Return True if the queue is empty, False otherwise (not reliable!)."""self.mutex.acquire()n &#61; not self._qsize()self.mutex.release()return ndef full(self):"""Return True if the queue is full, False otherwise (not reliable!)."""self.mutex.acquire()n &#61; 0 < self.maxsize &#61;&#61; self._qsize()self.mutex.release()return ndef put(self, item, block&#61;True, timeout&#61;None):self.not_full.acquire()try:if self.maxsize > 0:if not block:if self._qsize() &#61;&#61; self.maxsize:raise Fullelif timeout is None:while self._qsize() &#61;&#61; self.maxsize:self.not_full.wait()elif timeout < 0:raise ValueError("&#39;timeout&#39; must be a non-negative number")else:endtime &#61; _time() &#43; timeoutwhile self._qsize() &#61;&#61; self.maxsize:remaining &#61; endtime - _time()if remaining <&#61; 0.0:raise Fullself.not_full.wait(remaining)self._put(item)self.unfinished_tasks &#43;&#61; 1self.not_empty.notify()finally:self.not_full.release()def put_nowait(self, item):"""Put an item into the queue without blocking.Only enqueue the item if a free slot is immediately available.Otherwise raise the Full exception."""return self.put(item, False)def get(self, block&#61;True, timeout&#61;None):self.not_empty.acquire()try:if not block:if not self._qsize():raise Emptyelif timeout is None:while not self._qsize():self.not_empty.wait()elif timeout < 0:raise ValueError("&#39;timeout&#39; must be a non-negative number")else:endtime &#61; _time() &#43; timeoutwhile not self._qsize():remaining &#61; endtime - _time()if remaining <&#61; 0.0:raise Emptyself.not_empty.wait(remaining)item &#61; self._get()self.not_full.notify()return itemfinally:self.not_empty.release()def get_nowait(self):"""Remove and return an item from the queue without blocking.Only get an item if one is immediately available. Otherwiseraise the Empty exception."""return self.get(False)def _init(self, maxsize):self.queue &#61; deque()def _qsize(self, len&#61;len):return len(self.queue)# Put a new item in the queuedef _put(self, item):self.queue.append(item)# Get an item from the queuedef _get(self):return self.queue.popleft()Queue.Queue