The Wayback Machine - https://web.archive.org/web/20240414171219/https://github.com/stackless-dev/stackless/wiki/Pickling
Skip to content

Pickling

Anselm Kruis edited this page Jan 1, 2016 · 1 revision

Pickling

One of the main features of Stackless is its ability to pickle and unpickle tasklets. That means that a running program inside a tasklet can be persistently stored to a file or string. Later, it can be restored again and can continue to run at the point where it was previously halted. This need not be on the same machine!

Example - Pickling and unpickling simple tasklets:

Custom Tasklet or Channel Subclasses

Subclassing the tasklet or channel classes is pretty straightforward. In fact, if you need to persist any extra information with your tasklets or channels, you will need to do this. Neither of the classes have their slots or instance dictionary persisted with them when pickled.

The following example should illustrate exactly what the problem is.

Example - Named tasklets:

Output:

>>> print t2.name == t1.name
False
>>> print t2.name
'UNNAMED'

However, you can easily get around this by overriding __reduce__() / __reduce_ex__() and __setstate__() to add whatever else you want to be persisted.

Example - Named tasklets that persist their name:

Output:

>>> print t2.name == t1.name
True
>>> print t2.name
'Pointless'

Tasklets

Pickling a tasklet that is blocked on a channel, will not result in the pickling of that channel unless you are explicitly pickling a reference to that channel along with it.

If a tasklet is blocked on a channel that is not in any scope contained in the function the tasklet is bound to, then it will not be pickled.

Example - Channel not pickled:

Example - Channel pickled:

Channels

Pickling a channel, will also pickle any tasklets currently blocked on it. But sometimes you just want to pickle the channel with only some of those tasklets still blocked on it, or perhaps, tasklets you isolate from the channel on their own. You can do this by using __reduce__() and __setstate__().

Example - Removing a tasklet from a channel and pickling the results:

Two important things to know about the values you get from __reduce__() and pass to __setstate__():

  • The list of tasklets, featured in both functions, is in the order in which the tasklets came to be blocked on the channel.
  • When passed to __setstate__() the actual balance value is not used, except for its sign, which is used to indicate whether the blocked tasklets are receiving or sending.