Interrput a thread

Adam Skutt askutt at gmail.com
Mon Jan 3 18:10:10 EST 2011


On Jan 3, 5:05 pm, gervaz <ger... at gmail.com> wrote:
> Regarding the case pointed out by Adam I think the best way to
> deal with it is to create a critical section so that the shared memory
> will be updated in an atomic fashion.

Ok, so if the OS kills the process between taking the lock and
releasing it, what are you going to do?  Handled naively, you can end
up in a deadlock situation[1]. If a process has locked a semaphore and
then terminates, the semaphore retains its current value: all other
processes waiting on the semaphore will still be waiting, and any new
processes that access the semaphore will wait as well.  In short, if a
process holding a semaphore dies, you have to manually unlock it.

For signals that the process intends to handle, you can always disable
them before taking the lock and reenable them after releasing it.  Or,
you can install signal handlers in each process that ensure everything
is properly cleaned up when the signal is delivered.  Which solution
is right depends on what you're doing.

For signals you don't intend to handle (SIGSEGV) or cannot handle
(SIGKILL) there's not much you can do.  It's potentially dangerous to
continue on after a child has received such a signal, so the right
solution may be to literally do nothing and let the deadlock occur.
If you must do cleanup, it must be done carefully.  The key thing to
understand is that the problems with killing threads haven't gone
away: delivering the "please die" message isn't the hard part; it's
safely cleaning up the thread in such a way it doesn't break the rest
of the application!  This problem still exists if you replace threads
with processes (assuming you're using shared memory).

As such, the better thing to do, if possible, is to avoid shared
memory and use constructs like pipes and sockets for I/O.  They have
much better defined failure semantics, and do allow you a modicum of
fault isolation.  At the very least, graceful shutdown is much easier.

HTH,
Adam

[1] For SIGINT from the terminal, the "right thing" /might/ happen.
Strong emphasis on the might.



More information about the Python-list mailing list