From: "[email protected]" <[email protected]>
To: [email protected]
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 <[email protected]>
To: The Stackless Python Mailing List <[email protected]>
Subject: [Stackless] tasklet sleep()
Message-ID:
    <CAKtD2Vy=jwv-4a6-npt-bwcj75h_5j4tjna3_sp10vf26y2...@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()
_______________________________________________
Stackless mailing list
[email protected]
http://www.stackless.com/mailman/listinfo/stackless

Reply via email to