易截截图软件、单文件、免安装、纯绿色、仅160KB

Python 线程同步队列

我们经常会采用生产者/消费者关系的两个线程来处理一个共享缓冲区的数据。例如一个生产者线程接受用户数据放入一个共享缓冲区里,等待一个消费者线
程对数据取出处理。但是如果缓冲区的太小而生产者和消费者两个异步线程的速度不同时,容易出现一个线程等待另一个情况。为了尽可能的缩短共享资源并以相同
速度工作的各线程的等待时间,我们可以使用一个“队列”来提供额外的缓冲区。
创建一个“队列”对象
import Queue
myqueue = Queue.Queue(maxsize = 10)
Queue.Queue
类即是一个队列的同步实现。队列长度可为无限或者有限。可通过Queue
的构造函数的可选参数maxsize
来设定队列长度。如果maxsize
小于1
就表示队列长度无限。
将一个值放入队列中
myqueue.put(10)
调用队列对象的put()
方法在队尾插入一个项目。put()
有两个参数,第一个item
为必需的,为插入项目的值;第二个block
为可选参数,默认为1
。如果队列当前为空且block
为1
,put()
方法就使调用线程暂停,直到空出一个数据单元。如果block
为0
,put
方法将引发Full
异常。
将一个值从队列中取出
myqueue.get()
调用队列对象的get()
方法从队头删除并返回一个项目。可选参数为block
,默认为1
。如果队列为空且block
为1
,get()
就使调用线程暂停,直至有项目可用。如果block
为0,队列将引发Empty
异常。
我们用一个例子来展示如何使用Queue
# queue_example.py
from Queue import Queue
import threading
import random
import time
# Producer thread
class Producer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'adding',i,'to queue'
self.sharedata.put(i)
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Consumer thread
class Consumer(threading.Thread):
def __init__(self, threadname, queue):
threading.Thread.__init__(self, name = threadname)
self.sharedata = queue
def run(self):
for i in range(20):
print self.getName(),'got a value:',self.sharedata.get()
time.sleep(random.randrange(10)/10.0)
print self.getName(),'Finished'
# Main thread
def main():
queue = Queue(


相关文档:

python 的函数Decorators

Decorators是python中比较难以理解的东西,当然如果你接触过java的annotation,会发现这个Decorators在语法上非常的相似,但是两者的设计动机却没什么共同点;
这里讲的python中的decorators是对python中的function/method做装饰,这些修饰仅是当声明一个函数或者方法的时候,才会应用的额外调用。
python中的decorator分 ......

python 的time模板翻译及说明

python 的内嵌time模板翻译及说明
一、简介
time模块提供各种操作时间的函数
说明:一般有两种表示时间的方式:
第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的
第二种以数组的形式表示即(struct_time),共有九个元素,分别表示,同一个时间戳的struct_time会因为时区不同而不同
year ......

Python获取操作系统版本信息

    最近,想在我的YouMoney(http://code.google.com/p/youmoney/)里面增加提取用户操作系统版本信息。比如windows用户,可能要返回Windows XP ,或者Windows 2003, 苹果用户应该返回Mac OS X 10.5.8。用了很多办法,包括在mac系统里调用系统命令,取环境变量,等等。最后无意发现,原来python里里面有个pl ......

python string和PyQt的QString的区别

python string和PyQt的QString的区别 以下在Python2.6和PyQt4.4.4 for
Python2,6环境下讨论: Python中有两种有关字符的类型:Python string object和Python Unicode
object。主要使用Python string object进行数据输入输出。 PyQt中与之相对应的字符有关类
python string和PyQt的QString的区别
以下在Python2.6和PyQt4 ......
© 2009 ej38.com All Rights Reserved. 关于E健网联系我们 | 站点地图 | 赣ICP备09004571号