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

I'm trying to get a script to become as multithreaded as possible on a WinNT system. I understand that threads aren't supported yet (or I can't seem to find a binary compiled with threads for NT) so I was looking at forks. I must be a moron because I can't seem to understand how Forks work. Does anyone know where I can find a clean simple example? All I'm wanting to do is fire off about 20 threads trying to download certain web sites (feed in through STDIN) and return the status if they were successful or not to the parent. Any help is appreciated!

Replies are listed 'Best First'.
(tye)Re: Forks/Threads
by tye (Sage) on Feb 03, 2001 at 04:44 UTC

    fork() in Win32 Perl is experimental and doesn't really work very well.

    Use LWP::Parallel instead.

            - tye (but my friends call me "Tye")
Re (tilly) 1: Forks/Threads
by tilly (Archbishop) on Feb 03, 2001 at 04:50 UTC
Re: Forks/Threads
by Trinary (Pilgrim) on Feb 03, 2001 at 04:37 UTC
    fork

    Basically, you call it once, it returns twice. If it's the child, it returns 0. If the parent, returns the child's PID. So, from Camel:

    if ($pid = fork) { # parent here. } elsif (defined $pid) { #child here. }
    Left out some error checking stuff. make sure you wait for your child processes, or your parent will terminate and leave the kids hangin. Read up on fork, wait, and check out $SIG{CHLD} for handling forks. It's a confusing subject at first, but you'll soon pick it up.

    Enjoy!

    Trinary

      Thanks for the pointers! They helped a lot. So I've written a little test program to play with the forks and have included it below. Is there any problem with the way I'm keeping track of the max amount of forks to run at a given time? It seems to work fine but was wondering if there's something I'm not aware of or perhaps a better way.

      my $max_children = 10; # max number of children my $num_children = 0; # number we have now foreach $item (@items) { if( my $p = fork() ) { if ($num_children >= $max_children) { $dead_child = wait; $num_children--; } $num_children++; # child count } else { #do some sort of child processing last; # We want out of the loop } }

      Edit: 2001-03-03 by neshura