如何使用Stackless Python
安装stackless
下载地址
使用stackless
对象细节
- tasklet对象(完成对象的创建)
import stackless
def show():
print "Stackless Python"
st = stackless.tasklet(show)()
st.run()
st = stackless.tasklet(show)()
print st.alive
st.kill()
print st.alive
print stackless.tasklet(show)()
print stackless.tasklet(show)()
stackless.run()
- schedule对象(控制执行的顺序)
import stackless
def show():
stackless.schedule()
print 1
stackless.schedule()
print 2
print stackless.tasklet(show)()
print stackless.tasklet(show)()
stackless.run()
- channel对象(线程间通讯)
import stackless
def send():
chn.send("Stackless Python")
print "I send: Stackless Python"
def rec():
print "I receive:", chn.receive()
chn = stackless.channel()
print stackless.tasklet(send)()
print stackless.tasklet(rec)()
stackless.run()
综合应用
# -*- coding: utf-8 -*-
#
import stackless
import Queue
def Producer(i):
global queue
queue.put(i)
print "Producer", i, "produces", i
def Consumer():
global queue
i = queue.get()
print "Consumer", i, 'comsumes', i
queue = Queue.Queue()
for i in range(10):
stackless.tasklet(Producer)(i)
for i in range(10):
stackless.tasklet(Consumer)()
stackless.run()
什么是Stackless Python
Stackless Python是Python的一个增强版本,提供了对微线程的支持。微线程是轻量级的线程,微线程在多个线程之间切换所需的时间少,占用资源也更少。