in reply to how can I detach a thread from another or how can I set a timer for a thread?

At line #35
$thr_1->detach();
Delete that line. Then on line #12 add detach:
$thr_2 = threads->create('func_thr_2')->detach;
The script:
#!/usr/bin/perl use strict; use warnings; use threads; my $thr_1; my $thr_2; my $timer = 3; my $res; $thr_1 = threads->new('func_thr_1'); $thr_2 = threads->create('func_thr_2')->detach; $res = $thr_1->join(); print "exit code is: $res\n"; print "\nend\n"; sub func_thr_1 { my $cc = 0; print "thread 1 is running\n"; while ($cc <= 10) { print "cout is $cc\n"; sleep 1; $cc++; } return 'success'; } sub func_thr_2 { while ($timer >= 0) { $timer--; sleep 1; } print "\nTime up\n"; }

Replies are listed 'Best First'.
Re^2: how can I detach a thread from another or how can I set a timer for a thread?
by boeingdream (Novice) on Nov 11, 2011 at 06:14 UTC

    Sorry, I misunderstand detach(). Actually, what I want is terminating $thr_1 when time's up in $thr_2

    I have to write it with an old perl version v5.8.8 built for x86_64-linux-thread-multi. So there is no exit() or kill() available in the module.

      Sorry, I misunderstand detach()

      When a thread reaches the end of it's code block, or is issued a return, it sits and waits with it's return values, for the main thread to join it back in. When you detach the thread, the main thread no longer keeps count of it, and dosn't wait around for any return values. When a detached thread ends, it just goes away, instead of sitting there waiting to be joined.

      If you are using the old 5.8.8 version of threads, you will have to do a bit more work, because, as you say, many thread methods are missing in 5.8.8. You will have to rely on older hacks and work-arounds, for instance see Re: Backticks and SIGALRM


      I'm not really a human, but I play one on earth.
      Old Perl Programmer Haiku ................... flash japh

        Yes, the difference is whether or not you care about the final status (return code, etc.) of the thread.   If you do, it sits as a sort of “zombie” until you join it.   (The zombie status exists so that you can rendezvous without encountering race-conditions etc. ...)   If you don’t care, you can just detach the thread and it will perish on its own.

        Thanks a lot, it works for me. May I bother you with another question? I saw some code like:

        $pid = open my $fh, "$cmd |" or die "$!, $^E";

        Could you please tell me what does it mean by '$^E'

        I google it, but nothing useful.