[D-runtime] A mechanism to kill threads

Alex Rønne Petersen xtzgzorex at gmail.com
Wed May 16 18:08:32 PDT 2012


Actually removing the thread from the global thread list would be bad,
since the pthread cleanup callback will most likely access it. So, I
see two ways to solve this:

a) Once the thread has been scheduled for termination, join it
immediately and pray that everything goes well, and then remove it
from the global list. This won't work if the code inside the thread
has altered its cancelability state with
pthread_setcancel[state,type], but I don't think this is worth
worrying about. If someone uses those functions and tries to kill the
thread, they probably know what they are doing and are prepared for
the consequences of calling the kill function with a thread in a
non-cancelable state (it's actually not necessarily problematic as
long as they obey the cancellation request inside the thread -
obviously, it's threading library-specific, though).
b) Enqueue the termination request, and just return immediately. This
means that the thread won't be removed from the global thread list
until something (i.e. thread_suspendAll) notices that it's dead
(!t.isRunning). While this is the easiest solution, I don't think it's
very clever; normally, you'd expect the thread to have terminated by
the time the kill function returns.

Personally, I'm in favor of (a).

The problem with guarantees about thread cleanup still stands, though.

Regards,
Alex

On Thu, May 17, 2012 at 2:55 AM, Alex Rønne Petersen
<xtzgzorex at gmail.com> wrote:
> One interesting question in designing a kill function is: Do we want
> to guarantee that it runs all the thread shutdown routines (see the
> shutdown code in thread_entryPoint)? I'm thinking that guaranteeing
> this is basically impossible, so I'm leaning towards no. The most I
> can see would be realistic is to remove the thread from the global
> thread list if enqueueing the termination request (pthread_cancel on
> POSIX, TerminateThread on Windows) succeeded.
>
> If we don't guarantee this, how much resource leakage are we looking at?
>
> Regards,
> Alex
>
> On Wed, May 16, 2012 at 7:04 PM, Alex Rønne Petersen
> <xtzgzorex at gmail.com> wrote:
>> Hi,
>>
>> In my virtual machine, I need to be able to kill daemon threads on
>> shutdown. The problem is that VM shutdown is *not* tightly coupled to
>> druntime shutdown; multiple VM instances can run in a process at any
>> given time, and can be started/stopped whenever. It doesn't appear
>> like there is any functionality in core.thread to achieve this.
>>
>> Is there any reason we don't have a Thread.kill() function?
>>
>> Regards,
>> Alex


More information about the D-runtime mailing list