threads and exception in wxPython

Thomas Heller theller at python.net
Wed Nov 3 15:02:09 EST 2004


Peter Hansen <peter at engcorp.com> writes:

> Nick Craig-Wood wrote:
>> Peter Hansen <peter at engcorp.com> wrote:
>>
>>> >>> t = T()
>>> >>> t
>>><T(Thread-7, started)>
>>> >>> asyncexc = ctypes.pythonapi.PyThreadState_SetAsyncExc
>>> >>> exc = ctypes.py_object(ValueError)
>>> >>> asyncexc(t.id, exc)
>>> 1
>>> >>> thread terminated!
>>>
>>> >>> t
>>><T(Thread-7, stopped)>
>> On a related subject, I'm trying to forcibly terminate a thread thats
>> already running.  I don't see any means of doing this in the docs.
>> Sending it an exception would be ideal.  Is the above the only way of
>> doing this?
>
> This isn't just a related subject, this is exactly what
> I was trying to do above.
>
> I have a test case here which is failing, however, because
> the exception is *not* being delivered asynchronously for
> some reason, but appears in the thread only when the thread
> is already terminating itself.  I'm still experimenting, but
> I will probably post the failing test case shortly for
> others to play with.

Can it be that the exception is delivered asynchronously, but still has
to be checked by some code somewhere (my guess would be ceval.c)?
It seems sys.setcheckinterval() plays a role here.

I'l append my script at the end, I have the impression that the thread
has to execute quite some byte codes before it notices the pending
exception.  That's the reason for the 'for i in range(100):' loop in the
thread.

Thomas

<code>
import thread, time, sys
from ctypes import pythonapi, py_object

##sys.setcheckinterval(1)

def run():
    while 1:
        time.sleep(0.3)
        for i in range(100):
            pass
        sys.stdout.write(".")

exc = ValueError(42)

t = thread.start_new_thread(run, ())
# allow the thread to start
time.sleep(1)

# raise exception in thread
print pythonapi.PyThreadState_SetAsyncExc(t, id(exc))


##print pythonapi.PyThreadState_SetAsyncExc(t, py_object(exc))

# allow thread to print the exception
time.sleep(1)
print "done"

</code>




More information about the Python-list mailing list