[Stackless] Simple Threading Support

Andrew Francis andrewfr_ice at yahoo.com
Sat Apr 12 17:08:38 CEST 2008

Hi Paul:

> import stackless as s
> results = (5,4,3,2,1)
> def runMe(i):
>     time.sleep(i)
>     print "%d: Hello from TID %d" % (i,t.thread_id)
> for i in results:
>     t = s.tasklet(runMe)(i)
>     s.run
>             As you can see what I had hoped to
> accomplish is to run
> 'time.sleep' a total of five times. I would assume
> that if it was
> threading properly it would finish the final thread
> before the first
> thread and supply unique thread IDs for each call.

There are a few problems with your programme. Also, a
light weight thread in Stackless Python is called a
tasklet. I don't know where your OS thread reference
is coming from.

The main problem with your program is that
time.sleep() will block the entire programme for the
given time period. This should have the effect of
running each tasklet roughly after the last finishes.
So the programme will take roughly 15 seconds to
complete rather than 5.

If you are willing to use Twisted, here is a simple
example that does what you want.

The essense is as follows -

1)For each tasklet a channel is created. 
2)A Twisted scheduling function, reactor.callLater is
called. After n seconds, the channel's send method
will be called with a parameter of None
3)The tasklet blocks on the channel
4)After n seconds, when reactor.callLater is
triggered, it will execute myChannel.send()
5)The tasklet will return from the channel.

#!/usr/bin/env python
Andrew Francis
April 12th, 2008

<song>Insight - Joy Division</song>

import stackless
import time
from   twisted.internet   import reactor
from   twisted.internet   import task

results = [5,4,3,2,1]

def runMe(result):
    startTime = time.time()
    print "I am tasklet #", result
    myChannel = stackless.channel()
    reactor.callLater(result, myChannel.send, None)
    print "tasklet#", result, "done", time.time() -

for result in results:



Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 

More information about the Stackless mailing list