Monday, 7 January 2013

Stackless Code - The Short Version

So my last couple of posts have been on installing Stackless Python and what exactly the Stackless bit of Stackless Python means. Now it's time for the short version of the example code and an alternate explanation of continuations. Prepare to be underawed.

With Stackless ou get tasklets and channels. Channels let you communicate between tasklets.

#!/usr/bin/env stackless
import stackless
def sendKidsToShops():
kids = 3
ch.send(kids)
print kids, "kids sent to the store"
def buySweeties():
n = ch.receive()
while n:
print "kid #", n, "is spending your money on candy."
n -= 1
#stackless.schedule()
ch = stackless.channel()
stackless.tasklet(sendKidsToShops)()
stackless.tasklet(buySweeties)()
stackless.run()
view raw stackles.py hosted with ❤ by GitHub
Running this you get:

kid # 3 is spending your money on candy.
kid # 2 is spending your money on candy.
kid # 1 is spending your money on candy.
3 kids sent to the store
view raw gistfile1.txt hosted with ❤ by GitHub
Now the third and final thing that Stackless offers is cooperative multitasking. To see how this works, just uncomment the line with stackless.schedule() in it and rune it again.

kid # 3 is spending your money on candy.
3 kids sent to the store
kid # 2 is spending your money on candy.
kid # 1 is spending your money on candy.
view raw gistfile1.txt hosted with ❤ by GitHub
That's about it really, but as you know it's not what you got it's how you use it. There's a much more detailed explanation of what we just did here and the point is that this allows you to use continuations.

See my next post An Alternate Explanation of Continuations

Good luck fellow travellers.

No comments:

Post a Comment