exilepanda has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, The below code comes from perlthrtut.
use threads; $thr = threads->new(\&sub1); # Spawn the thread $thr->detach; # Now we officially don't care any more sub sub1 { $a = 0; while (1) { $a++; print "\$a is $a\n"; sleep 1; } }
Not sure I missed some point somewhere. This script ends immediately without doing anything. ( I am on WinXP pro ) This will going fine(as expected) if I use join() instead.

Will somebody tell me :
1. Why the turn out is given in this way?
2. How to create a thread and then leave it alone ? ie, I don't want to be warned for some threads not joined.
I do wish can write the whole thread declaration in a line like this :

threads->create("t_sub1")->detach(); threads->create("t_sub2")->detach();

Thank you very much!

Replies are listed 'Best First'.
Re: detach for threads
by Khen1950fx (Canon) on Nov 15, 2011 at 11:09 UTC
    What's happening is what is supposed to happen. When you use 'detach', you're not interested in any return values; hence, the script does its work and exits without "apparently" doing anything. I'd suggest using 'join' instead of detach if you want the counter to return to STDOUT. Here's my attempt at a viable solution:
    #!/usr/bin/perl -slw use strict; use Time::HiRes qw(sleep); use threads 'exit' => 'threads_only'; my $thr = threads->create(\&new_func)->join(); $thr = threads->exit(); sub new_func { my $cnt = 0; print "Thread is running..."; while ($cnt <= 500) { print "Count is: $cnt"; sleep 0.002; ++$cnt; } return; }
Re: detach for threads
by Anonymous Monk on Nov 15, 2011 at 08:47 UTC
    See perlthrtut
    use threads; my $thr = threads->create(\&sub1); # Spawn the thread $thr->detach(); # Now we officially don't care any more sleep(15); # Let thread run for awhile sub sub1 { $a = 0; while (1) { $a++; print("\$a is $a\n"); sleep(1); } }
      O! Thanks I got it now. It ends not because the thread has a problem, but the main() ends.
        As you experiment more with threads, you may see the warning " A thread exited while %d other threads were still running", that is caused by the main thread finishing before the spawned threads. Also watch out for using "exit" or "die" in thread code blocks, that will exit the entire program.

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