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过程中,python界面的编程工具GTK-Python,但是界面的美观性不如Qt-Creator中的Qt-Designer,无法实现设计是视图绘制,有点让人失望。
网上发现有人介绍python Eric IDE,比较好奇,安装上看看吧:
&nb ......
python的C、c++扩展
http://blog.chinaunix.net/u3/110228/showart_2148725.html
python的强大不仅表现在其功能上,而且还表现在其扩展能力上。
使用C/C++很容易编写python的模块,扩展python的功能。
同时将性能要求比较高的代码使用C/C++编写,能更好的弥补
脚本语言执行速度慢的缺陷。
1. python的C语言扩展
1.1 ......
用python写的抓取天气预报的脚本
http://blog.chinaunix.net/u2/82009/showart_2166843.html
从昨天开始的看关于网络抓取的东西,而且自己的用的是awesome ,所以写了这个天气预报的脚本给我的awesome,这个天气脚本直接取下来的话是七天的天气预报从中国天气网上,我后面对它做了处理,用到了我的awesome上
效果:1日星 ......
python中的datetime module是专门处理时间相关内容的模块,功能很强大,但是反而显得比较复杂。
一下代码是用来求从mysql中取到的timestamp和当前时间比较,求时间差的方法
import datetime
lasttime=a.get_last_timestamp(sid=40)[-1]["last_time"] #取到timestamp
delta = datetime.datetime.now()-lasttime # ......
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 ......