[Stackless] tasklet sleep()

Andrew Francis andrewfr_ice at yahoo.com
Tue Aug 2 19:34:48 CEST 2011


From: "stackless-request at stackless.com" <stackless-request at stackless.com>
To: stackless at stackless.com
Sent: Tuesday, August 2, 2011 6:00 AM
Subject: Stackless Digest, Vol 91, Issue 1

Message: 1
Date: Mon, 1 Aug 2011 18:34:42 -0300
From: Fernando Miranda <fcmiranda at gmail.com>
To: The Stackless Python Mailing List <stackless at stackless.com>
Subject: [Stackless] tasklet sleep()
Message-ID:
    <CAKtD2Vy=JWV-4A6-NPt-BwcJ75H_5j4tjNA3_Sp10Vf26Y2tgQ at mail.gmail.com>
Content-Type: text/plain; charset=ISO-8859-1

>Hi there, I'm wondering which is the best way to implement a sleeping
>function in a tasklet without block the task pipeline. Any ideas?

An approach you can take is to use a reactor that under the hood supports a feature like select() or epoll()
which have a timeout option. In my case I use Twisted but asyncore should work. 

In the case of Twisted, all the work is done in tick(). The reactor.callLater is the function that schedules time related tasks. 
It takes three arguments: waitTime, a function, the function's arguments. The sleight-of-hand in tick() is that the function passes a 
channel to callLater then blocks on said channel. In another tasklet, the reactor as a part of the callLater, calls the channel which 
wakes up the blocked tasklet.

from twisted.internet                                 import reactor
from twisted.internet                                 import task

import stackless

def tick(seconds):
    tickCh = stackless.channel()
    reactor.callLater(seconds, tickCh.send, None)
    tickCh.receive()

def startTwisted():
    reactor.run()

def stopTwisted():
    reactor.callLater(1, reactor.stop)
    print "that's all folks"

def worker(waitTime):
    print "waiting ", waitTime," seconds"
    tick(waitTime)
    print "done"
    stopTwisted()

if __name__ == "__main__":
   l = task.LoopingCall(stackless.schedule)
   l.start(.001)
   stackless.tasklet(startTwisted)()
   stackless.tasklet(worker)(10)
   stackless.run()
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.stackless.com/pipermail/stackless/attachments/20110802/77e7fb0b/attachment.html>


More information about the Stackless mailing list