[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
"""
timer.py
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)
    myChannel.receive()
    print "tasklet#", result, "done", time.time() -
startTime

for result in results:
    stackless.tasklet(runMe)(result)

task.LoopingCall(stackless.schedule).start(.01)
stackless.tasklet(reactor.run)()    
stackless.run()

Cheers,
Andrew

__________________________________________________
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 




More information about the Stackless mailing list