zoukankan      html  css  js  c++  java
  • Python Queue队列

    queue is especially useful in threaded programming when information must be exchanged safely between multiple threads
    queue在使用多进程之间交换安全信息的时候特别有用
    class queue.Queue(maxsize=0) #先入先出
    class queue.LifoQueue(maxsize=0) #last in fisrt out 
    class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列 优先级最小最先取出
    exception queue.Empty 正常情况下当队列为空则阻塞,如果设置了get_nowaait则会报该异常
    Exception raised when non-blocking get() (or get_nowait()) is called on a Queue object which is empty.
    exception queue.Full 当设置了put_nowait,队列满时报异常

    Exception raised when non-blocking put() (or put_nowait()) is called on a Queue object which is full.

    Queue.qsize() 查看队列大小
    Queue.empty() #return True if empty   队列为空返回True
    Queue.full() # return True if full 
    Queue.put(itemblock=Truetimeout=None) 上传到队列 正常当Q满了 在put就阻塞 如果timeout为True 则等待多少秒后直接抛异常
    Queue.put_nowait(item)# 队列满直接抛异常
    Queue.get(block=Truetimeout=None) #上传到队列,队列空了阻塞
    Queue.get_nowait() 队列没数据直接抛异常
    Queue.task_done() # q.task_done() 在完成一项工作之后,q.task_done() 函数向任务已经完成的队列发送一个信号. 
    Queue.join(实际上意味着等到队列为空,再执行别的操作
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import queue
    class Foo(object):
        def __init__(self,n):
            self.n = n
    
    #q =  queue.Queue(maxsize=30)
    #q =  queue.LifoQueue(maxsize=30)
    q =  queue.PriorityQueue(maxsize=30)
    q.put((2,[1,2,3]))
    #q.put(Foo(1))
    q.put((10,1))
    q.put((3,1))
    q.put((5,30))
    q.task_done()
    q.join()
    print(q.get())
    print(q.get())
    print(q.get())
    print(q.get())

    生产者消费者模型

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    import threading,queue
    import time
    
    def consumer(n):
        while True:
            print("33[32;1mconsumer [%s]33[0m get task:  %s" % (n,q.get()))
            time.sleep(1)
            q.task_done()#每get一次包子,像其他进程告知队列信息
    def producer(n):
        count = 1
        while True:
            #time.sleep(1)
            #if q.qsize() <3:
            print("prodcer [%s] produced a new task : %s" %(n,count))
            q.put(count)
            count +=1
            q.join() #queue is emtpy # 等到队列为空在继续往下执行
            print("all taks has been cosumed by consumers...")
    
    q = queue.Queue()
    c1 = threading.Thread(target=consumer,args=[1,])
    c2 = threading.Thread(target=consumer,args=[2,])
    c3 = threading.Thread(target=consumer,args=[3,])
    p = threading.Thread(target=producer,args=["XiaoYu",])
    p2 = threading.Thread(target=producer,args=["LiuYao",])
    c1.start()
    c2.start()
    c3.start()
    p.start()
    p2.start()
  • 相关阅读:
    dev DEV控件:gridControl常用属性设置
    C# ListView用法详解
    LeetCode 22_ 括号生成
    LeetCode 198_ 打家劫舍
    LeetCode 46_ 全排列
    LeetCode 121_ 买卖股票的最佳时机
    LeetCode 70_ 爬楼梯
    LeetCode 53_ 最大子序和
    LeetCode 326_ 3的幂
    LeetCode 204_ 计数质数
  • 原文地址:https://www.cnblogs.com/Chen-PY/p/5288122.html
Copyright © 2011-2022 走看看