#!/usr/bin/perl -wI .
#
use strict;

use Config; #it is still possible to compile Perl without thread 
    # support and there are older versions that do not support threads 
    # too.  Config will allow us to check.  Generally threads are 
    # available.  Good code, like this, checks, just in case.

use Time::HiRes qw( gettimeofday);  #since timing things

use threads;    #we need the libraries

$Config{useithreads} or
    die('Your version of Perl does not support required threads');

my @active;	#we will keep a list of the threads we started here

my $start1 = gettimeofday();	#when did we start the threads
for (my $i=0;$i<3;$i++) { #create three threads, workers
    my $thread = threads->create(\&f,$i * 10000000,10000000); 
        #make a thread to sum this group
        # When we create a thread we pass Perl a reference to
        # the subroutine to initiate as the thread and any
        # arguments that we wish to pass to the subroutine.
    push(@active,$thread); #and remember the thread object created
}


print "I am the boss and I created ", scalar @active, " threads\n"; 

my $realSum = 0;	#we will add the results from the workers here
while (my $this1 = shift(@active)) { #we need to check on each worker
    my $x = $this1->join(); #see what it returned, join() will wait
                        # for it to return 
    $realSum += $x;     #and what he gave us, the routine return value
}
print "The total as calculated by the threads is $realSum\n";
my $elapsed = gettimeofday() - $start1;
print "The threaded version took $elapsed seconds\n";

#now just use the same subroutine to make the same sum unthreaded
$start1 = gettimeofday();	#when did we start the regular version
print "And just doing it here generates " , f(0,30000000) , "\n";
$elapsed = gettimeofday() - $start1;
print "The inline version took $elapsed seconds\n";
exit(0);

sub f { #a silly routine to sum numbers, not very efficiently
    my $myStart = shift; #the start of the range to sum
    my $number = shift; #the number that we are to sum
    my $sum = 0;	#what sum I am making
    while ($number) { #add till we are done
        $sum += ($myStart + $number--); #add this value from
    }               # the range and reduce the number to do
    return $sum; #what we made for 'our' portion (range)
}
