#!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; my %totals :shared; my $stop :shared = 0; sub thread_worker { my $n = shift; # thread N my @args = shift; my %temp = (); print("Thread $n started: ", join(' ', @args), "\n"); my $s=0; while(1) { my $random = rand(); print "I'm thread $n, step $s, random num $random\n"; # each thread has its own hash to store the results # on each step of the loop we add (loop_step_number->random_value_generated) into hash # /me: waisting memory using temp hash, I don't know how to get around syntax of share() # $totals{$n}->{STEPS} = $s; # record step $temp{$s}=$random; # add value to per-thread hash $totals{$n}->{HASH}= &share( \%temp ); # copy results to shared structure $s++; sleep 1; sleep 70 if $stop; # stopping calculation by going into log sleep } } ## launch threads my @thr = (); for(my $i = 0; $i <= 9; $i++ ) { $totals{$i} = &share( { STEP=>0, HASH=>0} ); # create a datastructure for each thread $thr[$i] = threads->create('thread_worker', $i, 'ar gy ment'); $thr[$i]->detach(); } sleep 2; # let's give threads some time to work $stop =1; # stop all worker threads # now check results of the workers while ( my ($thread_num, $results) = each %totals ) { print "thread $thread_num, completed " . ($results->{STEPS} +1) . " steps\n"; for (my $st=0; $st <= $results->{STEPS}; $st++) { print "\t step: $st random value: $results->{HASH}->{$st}\n"; } }