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(
相关文档:
1.c调用python:
实例代码:
main.c调用test.py的
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
//main.c
#include <windows.h>
......
下载安装MySQLdb
http://sourceforge.net/projects/mysql-python/ 好像没看到windows版本for python2.6的下载,网上搜索到一个
http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe
安装后import MySQLdb会出现 DeprecationWarning: the sets module is deprecated 这样一个警告,google之
......
最近,想在我的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的区别 以下在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 ......