http://blog.csdn.net/crazy_fire/article/details/7506239
Queue是标准模块所以可以直接import,用起来就像是个真正的队列,先进先出的原则,这样进程间就可以用这个数据了,丫丫的,这个可好了。还是那个经典的生产者和消费者关系开始吧,书上讲的不通俗,记得记得学MFC时候那个孙鑫就介绍的比较容易接受。好了,切入主题。
有一个生产线,一个消费线,那么我们要做的就是消费的不能比生产的要多。脚本如下:
-
#!/usr/bin/env python
-
-
'''
-
Created on Apr 25, 2012
-
-
@author: stedy
-
'''
-
#coding=cp936
-
from random import randint
-
from time import sleep,ctime
-
from Queue import Queue
-
import threading
-
-
class MyThread(threading.Thread):
-
def __init__(self,func,args,name=""):
-
threading.Thread.__init__(self)
-
self.name = name
-
self.func = func
-
self.args = args
-
def getResult(self):
-
return self.res
-
def run(self):
-
print 'stating',self.name,'at',ctime()
-
self.func(*self.args)
-
-
def writeQ(queue):
-
i = randint(1,100)
-
print 'producing object for Q...',queue.put(i,1)
-
-
def readQ(queue):
-
if queue.empty() == False:
-
val = queue.get(1)
-
print 'value from Q',val
-
else:
-
print "no value,wait a moment"
-
sleep(1)
-
-
-
def writer(queue,loops):
-
for i in range(loops):
-
writeQ(queue)
-
sleep(randint(1,3))
-
-
def reader(queue,loops):
-
for i in range(loops):
-
readQ(queue)
-
sleep(randint(1,3))
-
-
funcs = [reader,writer]
-
nfuncs = range(len(funcs))
-
-
def main():
-
nloops = 99
-
q = Queue(100)
-
-
threads = []
-
for i in nfuncs:
-
t = MyThread(funcs[i],(q,nloops),funcs[i].__name__)
-
threads.append(t)
-
-
for i in nfuncs:
-
threads[i].start()
-
-
for i in nfuncs:
-
threads[i].join()
-
print 'all Done'
-
-
if __name__ == '__main__':
-
main()
运行结果
我们提取Queue的部分来看,首先是创建一个队列这是一个全局变量,当然是main内的’全局‘,这个变量给谁用呢?当然是给各个线程的函数用了,这里的数据就是能够共享的数据。
存入数据的函数是put简单吧,直接把数据给放入进去,取出的就是get也简单啊,不管你在函数的什么地方用都可以看到这两个函数那么我们开始担心的问题其实用这连个函数就可以搞定了,就是如果消费的数量多于生产的数量,put(value,block=0)如果我们将第二个参数设置不为0的数据,那么函数就等待到队列中有空间为止,那样线程不就挂起了吗,所以生产商就有时间生产了啊,同样如果get(block=0)函数如果参数不为0同样的等待队列有数据时候才退出。呵呵,这模样,队列这个东西很好用啊
阅读(2208) | 评论(0) | 转发(0) |