Synchronous signals vs. robust code

Toby Dickenson tdickenson at devmail.geminidataloggers.co.uk
Mon Feb 18 18:34:15 CET 2002


(reply posted, and cc to Mark)

Mark Mitchell <mark at codesourcery.com> wrote:

>Python provides synchronous signals, even though signals are
>asynchronous events at the operating system level.  In many ways,
>this is a Good Thing.  For example, in C you can't do much of anything
>from within a signal handler since you don't know much about the
>current state of the application,

>but in Python you can do just
>about anything.

The rest of your post proves that you know this isnt quite true.

>This code, however, is not signal-safe.  For example, if a signal
>occurs between the two calls to os.close, we will end up not closing
>the second descriptor.

No major damage is done if the exception ends up terminating this
python process, or if the exception is only caught after sufficient
objects have been destroyed that it has lost all reference counts on
the crucial file objects. 

>One solution, of course, is to make sure that the signal-handlers do
>not throw exceptions.  But that's not a reasonable solution in library
>code; the library can't go around deciding what signal handlers should
>be doing.

A library working to those standards is already in trouble without
introducing anything so tricky as a signal. In python almost any
operation can potentially raise an exception: function calls, slices,
and even assignments to globals or class attributes may involve memory
allocation which may fail.

Im guessing you have a C++ background, right? For the benefit of the
luck ones who dont, in C++ it is considered good style to use classes
with destructors to tidy up *all* resources used by a program, often
one class instance per resource, to ensure that all resources are
freed as an exception propagates up to its handler. Any half-complete
changes to an objects state are rolled back. These destructors can
only be written using operations that are guaranteed to *never* throw.

Python does not have this type of guaranteed-never-throws operation.
Therefore it is not possible to code in the C++-style.

For almost any non-trivial object, an exception can leave it in an
inconsistent state. The easiest option is for whoever catches the
exception to ensure it gets destroyed.


Toby Dickenson
tdickenson at geminidataloggers.com



More information about the Python-list mailing list