zoukankan      html  css  js  c++  java
  • 19、Python之队列

    一、队列的基本操作

        队列其实是一种数据结构,或者更本质的说队列其实就是对基本数据结构的封装,我们也可以封装自己的数据结构。队列做大的特点是先进先出FIFO(first in first out),下面我们就看看python中队列的基本操作。

    队列的基本操作如下:

     1 import queue
     2 
     3 # queue_01 = queue.Queue() #申明一个很大的队列
     4 queue_01 = queue.Queue(2) #申明一个长度为3的队列
     5 queue_01.put(1) #往队列中扔了一个数据
     6 queue_01.put(2)#又往队列中扔了一个数据
     7 queue_01.full() #判断队列是否满了
     8 # queue_01.put(3)#又往队列中扔了一个数据,如果队列满 则阻塞
     9 # queue_01.put(1,block=True)#如果队列满了,不阻塞
    10 # queue_01.put(1,timeout=2)#设置队列阻塞时间为1s
    11 queue_01.get()#从队列中取了一个数据
    12 queue_01.empty() #判断队列是否为空
    13 queue_01.get() #又从队列中取了一个数据
    14 # queue_01.get(block=True) #又从队列中取了一个元素,如果没有就阻塞
    15 # queue_01.get(block=False)#再从队列中取出一个数据,且不要阻塞,直接抛出异常
    16 #queue_01.get(timeout=1)#又从队列中取了一个元素,超时时间为1s
    17 
    18 #以下为特殊的队列
    19 q = queue.LifoQueue() #先进后出 --栈
    20 q2 = queue.PriorityQueue()#按照优先级取的队列
    21 q2.put((2,"hello"))
    22 q2.put((1,"python"))
    23 print(q2.get(),q2.get())
    View Code

    二、实例演示,生产者消费者模式

    实例代码如下:

     1 import  time,threading,queue
     2 
     3 MAX_SIZE = 2
     4 CUR_SIZE = 0
     5 q = queue.Queue()
     6 
     7 def producer(name):
     8     global  MAX_SIZE,CUR_SIZE
     9     while True:
    10         time.sleep(0.5)
    11         q.put(CUR_SIZE)
    12         print("33[41;1m%s生产了包子%s号33[0m" % (name,CUR_SIZE))
    13         CUR_SIZE = CUR_SIZE + 1
    14         if CUR_SIZE > MAX_SIZE:
    15             print("关门了!")
    16             break
    17 
    18 def consumer(name):
    19     global MAX_SIZE,CUR_SIZE
    20     while True:
    21         if q.qsize() <= 0 and CUR_SIZE<= MAX_SIZE:
    22             print("%s:没包子吃了,快点!" % name)
    23             time.sleep(1)
    24         elif CUR_SIZE>MAX_SIZE and q.qsize() <= 0:
    25             print("%s:没包子吃喽,回家了!" % name)
    26             break
    27         else:
    28             data = q.get()
    29             print("%s 取了包子%s好,开始吃起了" % (name, data))
    30             time.sleep(3)
    31 
    32 
    33 p = threading.Thread(target=producer,args=("高文祥",))
    34 c = threading.Thread(target=consumer,args=("张惠",))
    35 c_1 = threading.Thread(target=consumer,args=("gwx",))
    36 p.start()
    37 c.start()
    38 c_1.start()
    View Code

    执行结果

  • 相关阅读:
    HDU2586 How far away?(tarjan的LCA)
    You Raise Me Up
    POJ2891 Strange Way to Express Integers(中国剩余定理)
    POJ2142 The Balance(扩展欧几里得)
    HDU 1166模仿大牛写的线段树
    NetWord Dinic
    HDU 1754 线段树裸题
    hdu1394 Minimum Inversion Number
    hdu2795 Billboard
    【完全版】线段树
  • 原文地址:https://www.cnblogs.com/win0211/p/8549921.html
Copyright © 2011-2022 走看看