• python queue模块


     1 import queue
     2 # queue - A multi-producer, multi-consumer queue.
     3 # ['Empty', Exception raised by Queue.get(block=0)/get_nowait()
     4 #  'Full', Exception raised by Queue.put(block=0)/put_nowait()
     5 #  'LifoQueue',
     6 #  'PriorityQueue',
     7 #  'Queue',]
     8 
     9 
    10 # 1、Empty
    11 q = queue.Queue(3)
    12 q.get(block=False)   # 抛出Empty异常
    13 q.get_nowait()       # 抛出Empty异常
    14 
    15 # 2、Full
    16 q = queue.Queue(3)
    17 q.put(1)
    18 q.put(1)
    19 q.put(1)
    20 q.put(1, block=False)  # 抛出Full异常
    21 q.put_nowait(1)        # 抛出Full异常
    22 
    23 # 3、Queue
    24 # Create a queue object with a given maximum size.
    25 # If maxsize is <= 0, the queue size is infinite.
    26 q = queue.Queue(5)  # 创建一个长度为5的队列
    27 p = queue.Queue(0)  # 创建一个无限长度的队列
    28 # empty(self) Return True if the queue is empty, False otherwise (not reliable!).
    29 print(q.empty())
    30 # full(self) Return True if the queue is full, False otherwise (not reliable!).
    31 print(q.full())
    32 # put(self, item, block=True, timeout=None) Put an item into the queue.
    33 q.put(1)
    34 # get(self, block=True, timeout=None) Remove and return an item from the queue.
    35 print(q.get())
    36 # put_nowait(self, item) Put an item into the queue without blocking.
    37 print(q.put_nowait(2))
    38 # get_nowait(self) Remove and return an item from the queue without blocking.
    39 print(q.get_nowait())
    40 # qsize(self) Return the approximate size of the queue (not reliable!).
    41 print(q.qsize())
    42 # join(self) Blocks until all items in the Queue have been gotten and processed.
    43 # print(q.join())         # 阻塞put,等待全部get完
    44 # task_done(self) Indicate that a formerly enqueued task is complete.
    45 # print(q.task_done())    # 每次get完之后调用。
    46 
    47 
    48 # 4、LifoQueue继承Queue,栈
    49 # 方法同Queue
    50 q = queue.LifoQueue(5)
    51 q.put(1)
    52 q.put(2)
    53 q.put(3)
    54 q.put(4)
    55 print(q.get())  # 4
    56 print(q.get())  # 3
    57 print(q.get())  # 2
    58 print(q.get())  # 1
    59 
    60 
    61 # 5、PriorityQueue继承Queue
    62 # 方法同Queue,元素(priority number, data)
    63 q = queue.PriorityQueue(5)
    64 q.put((1, 'a'))
    65 q.put((4, 'd'))
    66 q.put((2, 'b'))
    67 q.put((3, 'c'))
    68 print(q.get())   # (1, 'a')   # 小的数先出
    69 print(q.get())   # (2, 'b')
    70 print(q.get())   # (3, 'c')
    71 print(q.get())   # (4, 'd')
  • 相关阅读:
    《构建之法》阅读笔记4
    团队冲刺第七天
    团队冲刺第六天
    团队冲刺第五天
    团队冲刺第四天
    团队冲刺第三天
    构建之法阅读笔记03
    第十四周进度条
    第二阶段冲刺站立会议10
    第二阶段冲刺站立会议09
  • 原文地址:https://www.cnblogs.com/gundan/p/8296662.html
Copyright © 2020-2023  润新知