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()