Re: is it possible to 'kill' a thread?



On Tuesday 17 January 2006 08:32, Paul Davis wrote:

> Cancelling a thread is a no no.  The general rule of thumb is to do what
> Ed here is saying.  You write your worker thread so that it checks some
> sort of status flag.  This solves a couple of problems, first and
> foremost, its implementation independant ( not to say that the actual
> calls are, unless you use something like Glib::Thread ; I imagine, I've
> only used pthreads cause like any normal *nix developer, I generally
> shun windows. </rant> )
>
> Anyway, that being said, if you do use something like pthreads, there is
> an alternative method.  pthread_signal is a way to signal threads.  It
> works quite a bit like normal process signaling, but on a per thread
> basis.  You can setup your thread signal masks on a per thread basis,
> and then send messages via signals in this manner.  There are some
> caveats.  First, you're gonna need a new enough implementation of
> pthreads. Second, but really part of the first, this is going to limit
> portability even between *nix distros.  I do alot of Tru64 / FC4
> development.  Its been awhile so I can't remember if Tru64 supports
> pthread_signal.

pthread_kill() is the POSIX version, but if the signal handler just sets a 
flag, what's the point?  If the threads are in the same process, since there 
is shared memory you can set a flag directly and be done with it (provided 
you use a mutex to ensure visibility).

Perhaps your proposal was to have the facility to use signals to interrupt 
blocking system calls which POSIX requires should return with an EINTR error 
in the presence of a signal where the SA_RESTART flag is not set, but 
programming this so that appropriate action is taken on every occasion that 
an asynchronous signal might be received (except by ending up just setting 
flags) seems to me to be a nightmare.  Setting flags in a signal handler also 
has the problem that it is difficult to ensure memory 
visibility/synchronisation on multi-processor systems - POSIX mutex functions 
are not async-signal-safe. You would probably have to use system specific 
memory barriers.

If you use blocking calls in the thread to be cancelled, I think the only 
workable approach is to use pthread_cancel().  pthread_cancel() is fine if 
you either use deferred cancelation together with correct and liberal use of 
pthread_setcancelstate() to limit the only permissible cancelation points to 
particular blocking functions of interest and control the object state at 
those points, or you use NPTL or the equivalent threading systems available 
on commercial UNIXes which will guarantee (as a C++ extension of the POSIX 
standard) to unwind the stack on cancelation.  I have to say I would prefer 
that to using pthread_kill().

Chris




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]