概述

        1)使用Stackless Python, 一定要先安裝。軟件下載網(wǎng)址: www.stackless.com

        2)stackless模塊的tasklet對(duì)象

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


>>> st = stackless.tasklet(show)()           #調(diào)用tasklet添加函數(shù),第二個(gè)括號(hào)為函數(shù)參數(shù)
>>> st.run()
Stackless Python
>>> st = stackless.tasklet(show)()
>>> st.alive                                              #顯示線程狀態(tài)
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()                                           #線程運(yùn)行完,也同樣顯示false
Stackless Python
>>> st.alive
False
>>> st = stackless.tasklet(show)()
>>> stackless.tasklet(show)()               #直接調(diào)用tasklet
<stackless.tasklet object at 0x00D19770>
>>> stackless.tasklet(show)()
<stackless.tasklet object at 0x00D2B8B0>
>>> stackless.run()
Stackless Python
Stackless Python
Stackless Python
>>>
>>>

3. 模塊中的schedule對(duì)象
>>> def show():
stackless.schedule()                     #使用schedule控制任務(wù)順序
print 1
stackless.schedule()
print 2


>>> stackless.tasklet(show)()        #調(diào)用tasklet,生成任務(wù)列表
<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 對(duì)象
>>> chn = stackless.channel()               #生成chn對(duì)象
>>> 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)                       #想隊(duì)列添加數(shù)據(jù)
    print 'Producer', i, 'add', i
   
def Consumer():
    global queue
    i = queue.get()                  #從隊(duì)列中取出數(shù)據(jù)
    print 'Consumer', i, 'get', i
   
queue = Queue.Queue()     #生成隊(duì)列對(duì)象
for i in range(10):
    stackless.tasklet(Producer)(i)
for i in range(10):
    stackless.tasklet(Consumer)()
   
stackless.run()