zoukankan      html  css  js  c++  java
  • 【Rollo的Python之路】Python 队列 学习笔记 queue

    Python 队列 学习笔记

    Queue是python标准库中的线程安全的队列(FIFO)实现,提供了一个适用于多线程编程的先进先出的数据结构,即队列,用来在生产者和消费者线程之间的信息传递

    基本语法:

    queue.Queue(self,maxsize=0)

    obj.put(item,block,timeout)来增加线程队列,将item 放入队列,如果block设置为True(默认为True)时,队列满时,调用者将被阻塞,否则抛出异常,timeout 设置阻塞超时

    obj.get()来取出线程队列,

    obj.objsize():返回队列的大小

    obj.full():如果队列满了返回True,否则为False

    obj.empty():如果队列为空,返回True,否则为False

    import queue
    
    d = queue.Queue(3) #几个队列,maxsize = 3,最大线程数量
    
    d.put('123') #加入线程
    d.put('456')
    d.put('789',0)  #0 多了就报错。
    
    print(d.get())#取值,是first in,first out,先进先出
    print(d.get())
    print(d.get())
    print(d.get(0)) #0 表示没了值取了就报错

    LifoQueue(maxsize): 后进先出的队列模式

    PriorityQueue(maxsize): 优先队列模式,使用此队列时,项目应该是(priority,data)的形式

    import queue
    import threading
    import time
    from random import randint
    
    class Production(threading.Thread):
        def run(self):
            while True:
                r = randint(0,100)
                q.put(r)
                print('生产出来%s号包子' %r)
                time.sleep(1)
    
    class Proces(threading.Thread):
        def run(self):
            while True:
                re = q.get()
                print('吃掉%s号包子' %re)
    
    
    if __name__ =="__main__":
        q = queue.Queue(10)
        threads = [Production(),Production(),Production(),Proces()]
        for t in threads:
            t.start()
  • 相关阅读:
    c# 一段生成6位不重复的随机数字码存8万个
    element ui 踩坑记
    Vue node.js 踩坑记
    javascript 异步回调链式调用 promise
    css 盒模型
    vue node.js 引入 linq
    Vue VsCode 项目 launch.json 文件
    node.js 基本语法识记
    Vue 2.0 入门示例识记
    在Windows系统中建立一个隐藏的帐户(在不登录界面显示)
  • 原文地址:https://www.cnblogs.com/rollost/p/10948347.html
Copyright © 2011-2022 走看看