笔记-python-standard library-17.7 queue

1.  queue

source code:Lib/queue.py

该模块实现了多生产者,多消费者队列。

此模块实现了所有的required locking semantics.

模块支持三种类型的队列,区别仅仅在于检索的顺序。

三种队列分别是FIFO,LIFO,优先级队列(使用heaq模块,优先抛出最小值)。

1.1.  模块中定义的类

class queue.Queue(maxsize=0)

class queue.LifoQueue(maxsize=0)

class queue.PriorityQueue(maxsize=0)

注意:优先级队列中优先抛出最小值。

exception queue.Empty

Exception raised when non-blocking get() (or get_nowait()) is called on a Queue object which is empty.

exception queue.Full

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

1.2.  类方法

三种队列类都提供了以下方法:

1.   Queue.qsize()返回队列大致的大小,注意qsize()>0不代表get不会阻塞,同样,qsize()<maxsize不代表put不会阻塞

2.   Queue.empty()

3.   Queue.full()

4.   Queue.put(item, block=True, timeout=None)

block决定是否阻塞,timeout决定最长阻塞时间

5.   Queue.put_nowait(item)

6.   Queue.get_nowait(): equal to get(False)

下面两个方法来跟踪队列中的任务是否被执行完。

7.   Queue.task_done()

8.   Queue.join()

阻塞直到队列中的所有任务完成。

其它属性

maxsize:队列最大长度,可以在初始化时给出,也可创建后手动设定。

1.1.    productor and consumer

queue实现生产者与消费者

q = queue.Queue()

def productor(arg):
    while True:
        if q.qsize()
< 30:
            q.put(str(arg)+'banana')
        time.sleep(1)

def consumer(arg):
    while True:
        print('con {},
pro {}'
.format(arg, q.get()))
        time.sleep(2)

for i in range(3):
    t = threading.Thread(target=productor,
args=(i,))
    t.start()

for j in range(5):
    t = threading.Thread(target=consumer,
args=(j,))
    t.start()

1.2.    task_done and join

文档如下:

def task_done(self):

'''Indicate that a formerly enqueued task is complete.

Used by Queue consumer threads. 
For each get() used to fetch a task,

a subsequent call to task_done() tells the queue that the processing

on the task is complete.

If a join() is currently blocking, it will resume when all items

have been processed (meaning that a task_done() call was received

for every item that had been put() into the queue).

Raises a ValueError if called more times than there were items

placed in the queue.

'''

with self.all_tasks_done:

unfinished = self.unfinished_tasks - 1

if unfinished <= 0:

if unfinished < 0:

raise
ValueError('task_done() called too many times')

self.all_tasks_done.notify_all()

self.unfinished_tasks = unfinished

关键是如果不使用task_done,阻塞不会结束,

下面的代码把红色行删掉,线程会阻塞在q.join()处,

q = queue.Queue()
q.maxsize = 100

def productor(arg):
    while True:
        if q.qsize()
>50:
            q.join()
        else:
            q.put(str(arg)+' banana')
        time.sleep(0.5)

def consumer(arg):
    while True:
        print('con {},
pro {}'
.format(arg, q.get()))
        q.task_done()
        time.sleep(2)

def start_t():
    for i in range(4):
        t = threading.Thread(target=productor,
args=(i,))
        t.start()

for j in range(5):
        t = threading.Thread(target=consumer,
args=(j,))
        t.start()

time.sleep(1)
    while True:
        q_length = q.qsize()
        if q_length
== 0:
            pass
           
#break
       
else:
            print("queue's
size is {}"
.format(q_length))
            time.sleep(2)

start_t()
time.sleep(0.5)
print(r'end {}')
print(threading.enumerate())

2.     
小结:

  1. queue是线程安全的
  2. FIFO实际使用的是dqueue,
  3. 在使用join时一定要使用task_done

笔记-python-standard library-17.7 queue的更多相关文章

  1. Python Standard Library

    Python Standard Library "We'd like to pretend that 'Fredrik' is a role, but even hundreds of vo ...

  2. The Python Standard Library

    The Python Standard Library¶ While The Python Language Reference describes the exact syntax and sema ...

  3. Python语言中对于json数据的编解码——Usage of json a Python standard library

    一.概述 1.1 关于JSON数据格式 JSON (JavaScript Object Notation), specified by RFC 7159 (which obsoletes RFC 46 ...

  4. 《The Python Standard Library》——http模块阅读笔记1

    官方文档:https://docs.python.org/3.5/library/http.html 偷个懒,截图如下: 即,http客户端编程一般用urllib.request库(主要用于“在这复杂 ...

  5. 《The Python Standard Library》——http模块阅读笔记2

    http.server是用来构建HTTP服务器(web服务器)的模块,定义了许多相关的类. 创建及运行服务器的代码一般为: def run(server_class=HTTPServer, handl ...

  6. 《The Python Standard Library》——http模块阅读笔记3

    http.cookies — HTTP state management http.cookies模块定义了一系列类来抽象cookies这个概念,一个HTTP状态管理机制.该模块支持string-on ...

  7. Python Standard Library 学习(一) -- Built-in Functions 内建函数

    内建函数列表 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() ...

  8. python类库32[多进程通信Queue+Pipe+Value+Array]

    多进程通信 queue和pipe的区别: pipe用来在两个进程间通信.queue用来在多个进程间实现通信. 此两种方法为所有系统多进程通信的基本方法,几乎所有的语言都支持此两种方法. 1)Queue ...

  9. [译]The Python Tutorial#11. Brief Tour of the Standard Library — Part II

    [译]The Python Tutorial#Brief Tour of the Standard Library - Part II 第二部分介绍更多满足专业编程需求的高级模块,这些模块在小型脚本中 ...

  10. C++11新特性——The C++ standard library, 2nd Edition 笔记(一)

    前言 这是我阅读<The C++ standard library, 2nd Edition>所做读书笔记的第一篇.这个系列基本上会以一章一篇的节奏来写,少数以C++03为主的章节会和其它 ...

随机推荐

  1. LotusScript_导出数据库路径和名称

    对服务器有些数据库需要建立复本,新建拷贝,修改权限(ACL),或是修改数据库标识符(ID)需要找到这些数据库.这个方法是导出指定服务器上所有数据库的路径,数据库名,标识符等信息,导出后对Excel表格 ...

  2. Android Vmp加固实现流程图

    0x00: 目前各种加固都说是VMP了,简单分析市面上的加固,然后自己实现了一个类似原理的加固,大致流程图如下: 加固端: 解释器:

  3. 夜色的 cocos2d-x 开发笔记 00

    第一次写博客,本人还是大二学生,纯新手,无论是文章的技术性,还是参考性,都不高,但却是根据我的经历,开发过的真实过程,对自己记载一些备忘的笔记,更希望也能帮到一些人. 本人用的win7 + vs201 ...

  4. 压力测试工具ab的使用

    ab是Apache自带的HTTP压力测试工具,全称是ApacheBench 路径为\Apache\bin\ab.exe 参数文档: http://httpd.apache.org/docs/2.2/p ...

  5. Java字体优化

    需求背景 最近在做的项目显示的字体感觉太丑,于是乎想着DIY改进一下. 查阅资料,总觉得别人写的都不咋地,于是决心写一篇略微完善点的关于项目字体优化方面的文章. 当然,这篇文章不会教你如何使用True ...

  6. python3绘图示例4(基于matplotlib:箱线图、散点图等)

    #!/usr/bin/env python# -*- coding:utf-8 -*- from matplotlib.pyplot import * x=[1,2,3,4]y=[5,4,3,2] # ...

  7. redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(多机)

    redis在Windows下以后台服务一键搭建哨兵(主从复制)模式(多机) 一.概述 此教程介绍如何在windows系统中多个服务器之间,布置redis哨兵模式(主从复制),同时要以后台服务的模式运行 ...

  8. 笨办法学Python(三十三)

    习题 33: While 循环 接下来是一个更在你意料之外的概念: while-loop``(while 循环).``while-loop 会一直执行它下面的代码片段,直到它对应的布尔表达式为 Fal ...

  9. sublime text2卸载和重新安装(转载)

    很多同学使用 sublime text2 的时候,出现一些奇怪的bug,且重启无法修复. 于是,就会想到卸载 sublime text2 再重新安装. 然而,你会发现,重新安装后,这个bug任然存在, ...

  10. 154. Find Minimum in Rotated Sorted Array II(Binary search)

    https://leetcode.com/problems/find-minimum-in-rotated-sorted-array-ii/description/ -- leetcode follo ...