in reply to using the thread->kill() feature on linux

I'm not really an expert on using signals, but I recently was looking into something like this myself on Windows. If you look into the documentation on thread signaling, you'll need to add a signal handler such as the code below taken verbatim from that documentation.

sub thr_func { # Thread 'cancellation' signal handler $SIG{'KILL'} = sub { threads->exit(); }; ... }

One word of caution about the code above. It will detach the thread, not "kill" it. I presume that when you say when you want a thread to die, you want it to completely stop what it's doing and to go away. A detached thread won't release its memory until the main code exits out. For me, that was a critical point since I was trying to write code that was intended to run forever and collect and record data every 15 minutes.

Replies are listed 'Best First'.
Re^2: using the thread->kill() feature on linux
by BrowserUk (Patriarch) on Oct 16, 2010 at 16:40 UTC
    A detached thread won't release its memory until the main code exits out.

    Um. That's simply not true. Detached threads release their memory as soon as they terminate.

    This is clearly demonstrated here. I start 100 threads that sleep for 3 seconds. I wait a second to ensure they are all running and then check the process memory usage, which stands at 59MB.

    I then wait another 5 seconds to ensure they all end, and check memory again. It's now 25MB.

    #! perl -slw use strict; use threads; sub checkmem { print qx[ tasklist /nh /fi "pid eq $$"]; } async(sub{ sleep 3 })->detach for 1 .. 100; sleep 1; checkmem; sleep 5; checkmem; __END__ c:\test>junk74 perl.exe 4928 Console 1 58 +,960 K perl.exe 4928 Console 1 24 +,696 K

    Not all the memory is released back to the OS--indeed, on some systems maybe none of it will be--but it has been released back to the process memory pool for re-use.

    Non-detached threads don't release their memory until joined, but detached thread release it as soon as they exit the thread sub.

    If you think you have code where this doesn't happen, please post it and we can work out what you're doing wrong.


    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.