#coding=utf-8
import time
import sys
# 生产者
def produce(l):
i=0
while 1:
if i < 5:
l.append(i)
yield i
i=i+1
time.sleep(1)
else:
return
# 消费者
def consume(l):
p = produce(l)
while 1:
try:
p.next()
while len(l) > 0:
print l.pop()
except StopIteration:
sys.exit(0)
l = []
consume(l)
在上面的例子中,当程序执行到produce的yield i时,返回了一个generator,当我们在custom中调用p.next(),程序又返回到produce的yield i继续执行,这样l中又append了元素,然后我们print l.pop(),直到p.next()引发了StopIteration异常。
通过上面的例子我们看到协程的调度对于内核来说是不可见的,协程间是协同调度的,这使得并发量在上万的时候,协程的性能是远高于线程的。
之前写过python线程池的实现http://www.iyunv.com/hymenz/p/3388492.html,下面我们用stackless来重写这部分的代码。
import stackless
import urllib2
def output():
while 1:
url=chan.receive()
print url
f=urllib2.urlopen(url)
#print f.read()
print stackless.getcurrent()
def input():
f=open('url.txt')
l=f.readlines()
for i in l:
chan.send(i)
chan=stackless.channel()
[stackless.tasklet(output)() for i in xrange(10)]
stackless.tasklet(input)()
stackless.run()
关于协程,可以参考greenlet,stackless,gevent,eventlet等的实现。