Views
Idioms
There are not that many idioms for Stackless Python that spring to mind. The reason for this is probably because it is straightforward to take advantage of and the most obvious gain comes from the change in code structure allowed by the use of tasklets and channels.
Sleeping
There is often a need to block a tasklet until a desired amount of time has passed. The simplest approach is to just reschedule it repeatedly, checking to see if the time to continue has arrived.
Idiom:
secondsToWait = 10.0
endTime = time.time() + secondsToWait
while time.time < endTime:
stackless.schedule()
However, having each tasklet that waits continually get rescheduled in order to recheck whether it should resume its activities can cause an unnecessarily heavy use of resources. It is convenient to write a common function that is called in order to block a tasklet until it should be awoken. Here is one way to do that.
Idiom - Sleep function for general use:
sleepingTasklets = []
def Sleep(secondsToWait):
channel = stackless.channel()
endTime = time.time() + secondsToWait
sleepingTasklets.append((endTime, channel))
sleepingTasklets.sort()
# Block until we get sent an awakening notification.
channel.receive()
def ManageSleepingTasklets():
while 1:
if len(sleepingTasklets):
endTime = sleepingTasklets[0][0]
if endTime <= time.time():
channel = sleepingTasklets[0][1]
del sleepingTasklets[0]
# We have to send something, but it doesn't matter what as it is not used.
channel.send(None)
stackless.schedule()
stackless.tasklet(ManageSleepingTasklets)()
Example - Sleep function in use:
def TestSleep()
print "pre", time.time()
Sleep(5.0)
print "post", time.time()
stackless.tasklet(TestSleep)()
stackless.run()
Output:
pre 1133381175.27 post 1133381180.28 <no more sleeping tasklets so ManageSleepingTasklets gets scheduled infinitely>
Stackless Python