概述

        1)使用Stackless Python, 一定要先安装。软件下载网址: www.stackless.com

        2)stackless模块的tasklet对象

>>> import stackless
>>> def show():
print 'Stackless Python'


>>> st = stackless.tasklet(show)()           #调用tasklet添加函数,第二个括号为函数参数
>>> st.run()
Stackless Python
>>> st = stackless.tasklet(show)()
>>> st.alive                                              #显示线程状态
True
>>> st.kill
<built-in method kill of tasklet object at 0x00D2B830>
>>> st.kill()                                              #杀掉线程
>>> st.alive
False
>>> st = stackless.tasklet(show)()
>>> st.alive
True
>>> st.run()                                           #线程运行完,也同样显示false
Stackless Python
>>> st.alive
False
>>> st = stackless.tasklet(show)()
>>> stackless.tasklet(show)()               #直接调用tasklet
<stackless.tasklet object at 0x00D19770>
>>> stackless.tasklet(show)()
<stackless.tasklet object at 0x00D2B8B0>
>>> stackless.run()
Stackless Python
Stackless Python
Stackless Python
>>>
>>>

3. 模块中的schedule对象
>>> def show():
stackless.schedule()                     #使用schedule控制任务顺序
print 1
stackless.schedule()
print 2


>>> stackless.tasklet(show)()        #调用tasklet,生成任务列表
<stackless.tasklet object at 0x00D190B0>
>>> stackless.tasklet(show)()
<stackless.tasklet object at 0x00D2B8B0>
>>> stackless.run()
1
1
2
2
>>> def show():                    #Remove schedule
print 1
print 2


>>> stackless.tasklet(show)()
<stackless.tasklet object at 0x00D19770>
>>> stackless.tasklet(show)()
<stackless.tasklet object at 0x00D2B8B0>
>>> stackless.run()
1
2
1
2
>>>
>>>
>>>
4. channel 对象
>>> chn = stackless.channel()               #生成chn对象
>>> def send():
chn.send('Stackless Python')
print "I send: Stackless Python"


>>> def rec():
print 'I receive:', chn.receive()


>>> stackless.tasklet(send)()
<stackless.tasklet object at 0x00D19770>
>>> stackless.tasklet(rec)()
<stackless.tasklet object at 0x01498330>
>>> stackless.run()
I receive: Stackless Python
I send: Stackless Python
>>>

 

9.4.2   使用微线程

# -*- coding:utf-8 -*-
# file: MP_MC.py
#
import stackless
import time
import Queue
def Producer(i):
    global queue
    queue.put(i)                       #想队列添加数据
    print 'Producer', i, 'add', i
   
def Consumer():
    global queue
    i = queue.get()                  #从队列中取出数据
    print 'Consumer', i, 'get', i
   
queue = Queue.Queue()     #生成队列对象
for i in range(10):
    stackless.tasklet(Producer)(i)
for i in range(10):
    stackless.tasklet(Consumer)()
   
stackless.run()