zoukankan      html  css  js  c++  java
  • python学习--queue 队列

    队列queue:

    作用:程序之间解耦;提高运行效率

    class queue.Queue(maxsize=0) #先入先出
    class queue.LifoQueue(maxsize=0) #last in fisrt out 
    class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列
    Queue.qsize()
    Queue.empty() #return True if empty  
    Queue.full() # return True if full 
    Queue.put(itemblock=Truetimeout=None)
    Queue.put_nowait(item)  #不等待,直接回复错误结果,避免卡死
    Queue.get(block=Truetimeout=None) #等待的时间只有timeout 秒
    Queue.get_nowait()
     1 import queue
     2 
     3 q = queue.Queue() #先入先出
     4 
     5 q.put("d1")
     6 q.put("d2")
     7 q.put("d3")
     8 print(q.qsize())
     9 print(q.get()) #取数据,按顺序取
    10 print(q.get())
    11 print(q.get())
    12 
    13 #q.get_nowait()  #不等待,直接回复错误结果,避免卡死
    14 #q.get(timeout=1)  #等待的时间只有1s
    15 #q.get()  #不能再取了,因为里面没有了,会卡死。
    16 
    17 q = queue.LifoQueue(3) #后入先出
    18 
    19 q.put("d1")
    20 q.put("d2")
    21 q.put("d3")
    22 print(q.qsize())
    23 print(q.full())  #判断是否队列存储满,返回布尔值
    24 print(q.empty())  #判断是否队列是否为空,返回布尔值
    25 print(q.get()) #取数据,按反序取
    26 print(q.get())
    27 print(q.get())
    28 
    29 
    30 q = queue.PriorityQueue(3) #优先级输出
    31 
    32 q.put((10,"d1"))
    33 q.put((11,"d2"))
    34 q.put((1,"d3"))
    35 print(q.qsize())
    36 print(q.full())  #判断是否队列存储满,返回布尔值
    37 print(q.empty())  #判断是否队列是否为空,返回布尔值
    38 print(q.get()) #取数据,按照优先级取,从小到大
    39 print(q.get())
    40 print(q.get())

    集群的基础:

    经典的生产者消费者模型

     1 import threading,time
     2 
     3 import queue
     4 
     5 q = queue.Queue(maxsize=10)
     6 
     7 
     8 def Producer(name):
     9     count = 1
    10     while True:
    11         q.put("%s 牌骨头%s" % (name, count))
    12         print("%s 生产了骨头 %s " % (name, count))
    13         count += 1
    14         time.sleep(0.1)
    15 
    16 
    17 def Consumer(name):
    18     #while q.qsize()>0:
    19     while True:
    20         print("[%s] 取到[%s] 并且吃了它..." % (name, q.get()))
    21         time.sleep(1)
    22 
    23 
    24 p = threading.Thread(target=Producer,args=("big dog",))
    25 c = threading.Thread(target=Consumer,args=("jojo",))
    26 c1 = threading.Thread(target=Consumer,args=("cj",))
    27 
    28 p.start()
    29 c.start()
    30 c1.start()
  • 相关阅读:
    关于在MAC上进行 LARAVEL 环境 Homestead 安装过程记录
    js 贷款计算器
    js 实现阶乘
    js 两点间距离函数
    composer Your requirements could not be resolved to an installable set of packages
    vue 项目优化记录 持续更新...
    vue 项目打包
    vue 真机调试页面出现空白
    vue 真机调试
    谈谈-Android状态栏的编辑
  • 原文地址:https://www.cnblogs.com/Ian-learning/p/11794877.html
Copyright © 2011-2022 走看看