Join the DZone community and get the full member experience.Join For Free
Today at work we had a presentation from the venerable Kristján Valur Jónsson about killing Tasklets in Stackless Python, a technique he and partner-in-crime Matthías Guðmundsson started using for their work on DUST514. As someone who’s done some asynchronous programming, this idea sounded blasphemous. It took a little while to stew but I see the value in it now.
The core idea is really simple. Code invokes the kill method on a tasklet. All kill does is synchronously raise a TaskletExit exception (which inherits from BaseException so as not to be caught by general error handling, same idea as SystemExit) on the tasklet. This bubbles up to the Stackless interpreter, and is caught and swallowed.
There are details of course, but that’s the gist. There are a few reasons I like this so much.
First, it uses standard Python exception handling. It’s really easy to explain and understand, like no question about finally blocks being executed (they are). The fact that the killed code runs and dies as I expect makes this at least something to look at.
Second, it can be synchronous. There’s no ‘kill and spin until it’s not alive’ type of thing. When you tell the tasklet to die, it faithfully obeys. You are Thulsa Doom. You can kill it asynchronously but the fact that synchronous behavior works in such a straightforward way is a big thing.
Third, it actually cancels the tasklet where it is. You cannot replicate this with some sort of cancellation token or flag, which always has some delay if it supports cancellation at all. It not only simplifies things but makes them work totally as desired. So even if you are theologically opposed to Tasklet.kill and prefer other disciplined techniques for writing async code, you can’t argue with the superior results.
In the end, you still need to write good code and maintain discipline about shared state and side effects, but I see not only the value in killing tasklets but the superiority of the choice. I hope Kristján (and also Christian Tismer, the other Christian primarily responsible for Stackless) do a more thorough talk about killing tasklets at some conference.
Published at DZone with permission of Rob Galanakis , DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.