Threading and Asynchronous Exceptions

IronPython and Threads

The good sides of threads...

Asynchronous Exceptions

Asynchronous exceptions are ones that can be raised at any point during code execution. They are generally considered to be evil, because it is virtually impossible to write code that can handle them.

A classic example of asynchronous exceptions is aborting threads. Python doesn't provide a way to abort a running thread, Java does (the stop method) but it is deprecated, C# threads have an Abort method. In both Java and C#, the thread is stopped by raising an exception; in Java the ThreadDeath error and in C# ThreadAbortException.

As this exception propagates up the stack of the thread, locked monitors are unlocked as it goes. Data these monitors are protecting may be left in an inconsistent state. An alternative is to use a state variable that another thread can use to signal the current thread that it's time to die.

Although Python doesn't have a mechanism for killing running threads, it does have two asynchronous exceptions: KeyboardInterrupt and MemoryError. MemoryError is usually pretty fatal anyway, but if you have any parts of your code that you expect to take a long time, you can catch the KeyboardInterrupt (from the user pressing 'crtl-c') and do the necessary cleaning-up.

Aborting Threads

In the same way that you catch keyboard interrupts, you can catch the thread stopping exceptions. This means that you can use a try ... finally block to release any resources that the thread is using before it exits.

This works fine most of the time. The problem with asynchronous exceptions though, is that they can happen any time; and that means inside the finally block which is doing the clean-up. Oops.

.NET 1.1 suffered from this problem, which made using Thread.Abort unreliable and unwise. Rather than deprecate it, they found a solution. In .NET 2.0, the ThreadAbortException will not be raised inside a finally block. It will only be raised once the code has left the finally block. This means of course, that an infinite loop in a finally block will stop the thread from exiting.

The next sections provide some simple examples of threading with IronPython, and illustrates using Thread.Abort. This doesn't mean that signalling to threads when to stop isn't generally a better technique, but (especially with a shared nothing model) it can sometimes be safe to abort threads.

Simple Threading

Simple threading in IronPython can be done with either the IronPython or the .NET interface. The .NET interface is basically as simple to use as the Python one. We use the Thread Class and ThreadStart Delegate from System.Threading:

>>> from System.Threading import Thread, ThreadStart
>>> def f():
...    Thread.Sleep(5000)
...    print 'Finished'
...
>>> t = Thread(ThreadStart(f))
>>> t.Start()
>>> Finished

The thread pauses for five seconds and then prints 'Finished' when it has completed.

Thread.Abort

We can kill the thread before it has finished, by calling the Thread.Abort method:

>>> from System.Threading import Thread, ThreadStart
>>> def f():
...    Thread.Sleep(5000)
...    print 'Finished'
...
>>> t = Thread(ThreadStart(f))
>>> t.Start()
>>> t.Abort()

So long as you manage to call the Abort method of the thread before the five seconds are up, 'Finished' is never printed.

Cleaning Up in a Finally Block

If we need to guarantee that a cleanup happens, we can put the cleanup in a finally block. This will complete execution, even if Thread.Abort is called whilst the code is in the finally block:

>>> from System.Threading import Thread, ThreadStart
>>> def f():
...     try:
...         print 'Started'
...     finally:
...         Thread.Sleep(5000)
...         print 'Finished'
...
>>> t = Thread(ThreadStart(f))
>>> t.Start()
Started
>>> t.Abort()
Finished

This example prints 'Started',and then pauses for five seconds inside the finally block. Even if you call Abort whilst the thread is sleeping inside the finally block, 'Finished' is still printed.

For buying techie books, science fiction, computer hardware or the latest gadgets: visit The Voidspace Amazon Store.

Hosted by Webfaction

Return to Top

Page rendered with rest2web the Site Builder

Last edited Fri Nov 27 18:32:35 2009.

Counter...