Ctrl-z has asked for the wisdom of the Perl Monks concerning the following question:


Im in the process of downloading Activstate 5.8 for Win32, and am keen to get some threading shenanigans going on.
Ive used the pseudo-fork() with some success in 5.6 and have some code I'd like to impliment in threads 'proper'.Ive read the perldocs and associated stuff, but am not totally sure I'm getting it - particularly where i should be join()ing.

consider this pseudo-fork() code

foreach (1..10) { my $pid; print "$$ starting loop $_"; if( $pid = fork()) { print "$$ created child $pid"; } else { print "\t", "child $$ created ok"; sleep(int(rand(10))); print "\t", "child $$ done, outta here"; exit; } print "$$ exiting loop $_" if $pid; } # 1 while wait != -1; # *cough* print "$$ all done!";
would this be a similar implementation using threads - and if so, where should i be join()ing or detach()ing?
use threads; foreach(1..10) { print "$$ starting loop $_"; my $kid = new threads(\&wasPsuedoFork); print "$$ exiting loop $_"; } sub wasPsuedoFork { print "\tchild ", threads->tid() " created ok"; sleep(int(rand(10))); print "\tchild", threads->tid() , " done, outta here"; }

Replies are listed 'Best First'.
Re: from pseudofork to threads
by pg (Canon) on Feb 02, 2003 at 17:28 UTC
    If you want it to be similar to your fork version, you don't want to detach, as a detached thread is no longer joinable.

    You want to do something like this:
    use threads; use strict; use constant NUMBER_OF_THREAD => 10; $|++; sub thread_job { print "I am a child, this is the name my parents gave me: ", shift +(), "\n"; } my @kids; for (1..NUMBER_OF_THREAD) { push @kids, threads->create(\&thread_job, $_); } foreach my $kid (@kids) { $kid->join(); } print "The family reunioned!";
Re: from pseudofork to threads
by Ctrl-z (Friar) on Feb 02, 2003 at 15:59 UTC
    hmm, i think ive got my answer here
    so for join(), that should be something like
    use threads; my @kiddies; foreach(1..10) { print "$$ starting loop $_"; push @kiddies, threads->new(\&thisWasAnElse); print "$$ exiting loop $_"; } sub thisWasAnElse { print "\tchild ", threads->tid() " created ok"; sleep(int(rand(10))); print "\tchild", threads->tid() , " done, outta here"; } foreach @kiddies { $_->join(); }
    can i safely detach() inside the first foreach loop?

    well the downloads complete, so lets see what happens...
      You can detach in the first loop, but as whether it is safe, really depeneds on what the child thread is doing.

      When the main thread exit, all child threads will be shut down at unpredictable point, it might seriously hurt what you are doing (, again really depends what it is doing).

      As far as Perl is concerned, that doesn't matter, although it will warn you that you exit when some threads running.