Re: is it possible to 'kill' a thread?
- From: Chris Vine <chris cvine freeserve co uk>
- To: gtkmm-list gnome org
- Cc: "B.Hakvoort" <bart hakvoort be>
- Subject: Re: is it possible to 'kill' a thread?
- Date: Mon, 16 Jan 2006 20:38:33 +0000
On Monday 16 January 2006 16:00, B.Hakvoort wrote:
> Hi,
>
> I was wondering if it's possible to end a thread from OUTSIDE that
> thread. I have a thread which executes an un-interruptable function and
> i'd like to end that execution whenever a user presses the 'cancel'
> button.
>
> I did some searching and found Glib::Thread::Exit, but i'm not sure how
> it can be usefull in this situation.
>
> Any insights in how to accomplish this the 'right' way?
You can't with GThread/Glib::Thread. However, if you know that pthreads is
the underlying implementation, you can use pthread_cancel(). I think Windows
has something similar.
Note that pthread_cancel() is a C function. When used in a program written
with C++, it is implementation defined whether the destructors of local
(automatic) objects are invoked (with linuxthreads they are not, but with
NPTL they are - and the same would apply to a call to g_thread_exit()).
Accordingly it is best to make no assumptions, and to choose the cancelation
point (with pthread_setcancelstate()) for a time when there are only built-in
types in local scope, and to use pthread_cleanup_push()/pthread_cleanup_pop()
for cleanup of other resources.
An alternative is to signal the thread concerned so that it will call
g_thread_exit() or throw Glib::Thread::Exit. However if you do this via the
main program loop (say, with a Glib::Dispatcher object) then the signalling
thread has no control over the time when the other thread will receive the
signal. However it becomes very easy for the receiving thread to arrange a
suitable time to commit suicide which cleans up properly when it receives the
signal (so that g_thread_exit() will be fine). But that in turn means that
the receiving thread cannot be in a blocking system function, and enabling
the use of blocking system calls is quite a common reason for using separate
threads in the first place. In that case you will have to call
pthread_cancel() from the other thread. Happily, in POSIX all blocking
system calls are cancelation points.
There may be problems with using Glib::Thread::Exit with NPTL - see
http://mail.gnome.org/archives/gtkmm-list/2005-June/msg00211.html and the
follow-ups - although that may have just been the user.
Chris
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]