Queue 模块

``Queue`` 模块提供了一个线程安全的队列 (queue) 实现, 如 [Example 3-2 #eg-3-2] 所示.
你可以通过它在多个线程里安全访问同个对象. ====Example 3-2. 使用 Queue 模块====[eg-3-2] ```
File: queue-example-1.py import threading
import Queue
import time, random WORKERS = 2 class Worker(threading.Thread): def _ _init_ _(self, queue):
self._ _queue = queue
threading.Thread._ _init_ _(self) def run(self):
while 1:
item = self._ _queue.get()
if item is None:
break # reached end of queue # pretend we're doing something that takes 10?00 ms
time.sleep(random.randint(10, 100) / 1000.0) print "task", item, "finished" #
# try it queue = Queue.Queue(0) for i in range(WORKERS):
Worker(queue).start() # start a worker for i in range(10):
queue.put(i) for i in range(WORKERS):
queue.put(None) # add end-of-queue markers *B*task 1 finished
task 0 finished
task 3 finished
task 2 finished
task 4 finished
task 5 finished
task 7 finished
task 6 finished
task 9 finished
task 8 finished*b*
``` [Example 3-3 #eg-3-3] 展示了如何限制队列的大小. 如果队列满了,
那么控制主线程 (producer threads) 被阻塞, 等待项目被弹出 (pop off). ====Example 3-3. 使用限制大小的 Queue 模块====[eg-3-3] ```
File: queue-example-2.py import threading
import Queue import time, random WORKERS = 2 class Worker(threading.Thread): def _ _init_ _(self, queue):
self._ _queue = queue
threading.Thread._ _init_ _(self) def run(self):
while 1:
item = self._ _queue.get()
if item is None:
break # reached end of queue # pretend we're doing something that takes 10?00 ms
time.sleep(random.randint(10, 100) / 1000.0) print "task", item, "finished" #
# run with limited queue queue = Queue.Queue(3) for i in range(WORKERS):
Worker(queue).start() # start a worker for item in range(10):
print "push", item
queue.put(item) for i in range(WORKERS):
queue.put(None) # add end-of-queue markers *B*push 0
push 1
push 2
push 3
push 4
push 5
task 0 finished
push 6
task 1 finished
push 7
task 2 finished
push 8
task 3 finished
push 9
task 4 finished
task 6 finished
task 5 finished
task 7 finished
task 9 finished
task 8 finished*b*
``` 你可以通过继承 //Queue// 类来修改它的行为. [Example 3-4 #eg-3-4]
为我们展示了一个简单的具有优先级的队列. 它接受一个元组作为参数,
元组的第一个成员表示优先级(数值越小优先级越高). ====Example 3-4. 使用 Queue 模块实现优先级队列====[eg-3-4] ```
File: queue-example-3.py import Queue
import bisect Empty = Queue.Empty class PriorityQueue(Queue.Queue):
"Thread-safe priority queue" def _put(self, item):
# insert in order
bisect.insort(self.queue, item) #
# try it queue = PriorityQueue(0) # add items out of order
queue.put((20, "second"))
queue.put((10, "first"))
queue.put((30, "third")) # print queue contents
try:
while 1:
print queue.get_nowait()
except Empty:
pass *B*third
second
first*b*
``` [Example 3-5 #eg-3-5] 展示了一个简单的堆栈 (stack) 实现
(末尾添加, 头部弹出, 而非头部添加, 头部弹出). ====Example 3-5. 使用 Queue 模块实现一个堆栈====[eg-3-5] ```
File: queue-example-4.py import Queue Empty = Queue.Empty class Stack(Queue.Queue):
"Thread-safe stack" def _put(self, item):
# insert at the beginning of queue, not at the end
self.queue.insert(0, item) # method aliases
push = Queue.Queue.put
pop = Queue.Queue.get
pop_nowait = Queue.Queue.get_nowait #
# try it stack = Stack(0) # push items on stack
stack.push("first")
stack.push("second")
stack.push("third") # print stack contents
try:
while 1:
print stack.pop_nowait()
except Empty:
pass *B*third
second
first*b*
```

python标准库介绍——32 Queue 模块详解的更多相关文章

  1. python标准库介绍——27 random 模块详解

    ==random 模块== "Anyone who considers arithmetical methods of producing random digits is, of cour ...

  2. python标准库介绍——12 time 模块详解

    ==time 模块== ``time`` 模块提供了一些处理日期和一天内时间的函数. 它是建立在 C 运行时库的简单封装. 给定的日期和时间可以被表示为浮点型(从参考时间, 通常是 1970.1.1 ...

  3. python标准库介绍——10 sys 模块详解

    ==sys 模块== ``sys`` 模块提供了许多函数和变量来处理 Python 运行时环境的不同部分. === 处理命令行参数=== 在解释器启动后, ``argv`` 列表包含了传递给脚本的所有 ...

  4. python标准库介绍——30 code 模块详解

    ==code 模块== ``code`` 模块提供了一些用于模拟标准交互解释器行为的函数. ``compile_command`` 与内建 ``compile`` 函数行为相似, 但它会通过测试来保证 ...

  5. python标准库介绍——8 operator 模块详解

    ==operator 模块== ``operator`` 模块为 Python 提供了一个 "功能性" 的标准操作符接口. 当使用 ``map`` 以及 ``filter`` 一类 ...

  6. python标准库介绍——36 popen2 模块详解

    ==popen2 模块== ``popen2`` 模块允许你执行外部命令, 并通过流来分别访问它的 ``stdin`` 和 ``stdout`` ( 可能还有 ``stderr`` ). 在 pyth ...

  7. python标准库介绍——23 UserString 模块详解

    ==UserString 模块== (2.0 新增) ``UserString`` 模块包含两个类, //UserString// 和 //MutableString// . 前者是对标准字符串类型的 ...

  8. python标准库介绍——22 UserList 模块详解

    ==UserList 模块== ``UserList`` 模块包含了一个可继承的列表类 (事实上是对内建列表类型的 Python 封装). 在 [Example 2-16 #eg-2-16] 中, / ...

  9. python标准库介绍——21 UserDict 模块详解

    ==UserDict 模块== ``UserDict`` 模块包含了一个可继承的字典类 (事实上是对内建字典类型的 Python 封装). [Example 2-15 #eg-2-15] 展示了一个增 ...

随机推荐

  1. 008-Go 关于字符串拼接

    如果是少量小文本拼接,用 “+” 如果是大量小文本拼接,用 strings.Join 如果是大量大文本拼接,用 bytes.Buffer package main import( "fmt& ...

  2. JAVA设计模式——第 1 章 策略模式【Strategy Pattern】(转)

    刘备要到江东娶老婆了,走之前诸葛亮给赵云(伴郎)三个锦囊妙计,说是按天机拆开解决棘手问题,嘿,还别说,真是解决了大问题,搞到最后是周瑜陪了夫人又折兵呀,那咱们先看看这个场景是什么样子的. 先说这个场景 ...

  3. Apache禁止显示目录结构

    打开文件:httpd-vhosts.conf: 禁止显示Apache目录列表-Indexes FollowSymLinks如何修改目录的配置以禁止显示 Apache 目录列表.缺省情况下如果你在浏览器 ...

  4. Excel Vlookup 列查找函数

    列查找函数语法:vlookup(lookup_value,table_array,col_index_num,[range_lookup]) lookup_value:要查找的值,数值.引用或文本字符 ...

  5. error:No buffer space available (maximum connections reached

    2015-02-02 17:49:09,035 ERROR basic.DBManager - Failded to establish the connection. com.mysql.jdbc. ...

  6. 转:折腾一晚上Bullet及Ogre相关工具的成果 -- 3Ds Max,Maya, blender, GameKit

    起始目的很简单,整合Bullet及Ogre,找个能够生成.scene和.bullet文件的建模工具. 折腾一晚上Bullet及Ogre相关的东西,基本上就像爱迪生发明灯泡一样,得出了N个失败的教训,总 ...

  7. 聊聊单元测试(三)——Spring Test+JUnit完美组合

    本着“不写单元测试的程序员不是好程序员”原则,我在坚持写着单元测试,不敢说所有的Java web应用都基于Spring,但至少一半以上都是基于Spring的. 发现通过Spring进行bean管理后, ...

  8. Ubuntu系统下添加程序启动器

    Ubuntu系统上安装的软件,有的会自动创建快捷方式,在程序中可以搜索到,而有的安装后不会在应用程序中出现,如Eclipse.Spring Tool Suite或是绿色软件等,那么怎么手动创建快捷方式 ...

  9. linux下淘宝安全控件问题

    2009-09-21  我的环境:ubuntu9.04 firefox3.0.14   下载压缩包http://blog.alipay.com/wp-content/2008/10/aliedit.t ...

  10. 有关memcached企业面试案例讲解

    有关memcached企业面试案例讲解 1.Memcached是什么,有什么作用?    a. memcached是一个开源的.高性能的内存的缓存软件,从名称上看Mem就是内存的意思,而Cache就是 ...