#! perl -slw use strict; use Time::HiRes qw[ time ]; use threads; use Thread::Queue; sub x { my( $str, $v1, $v2 ) = @_; my $result =0; $result += (ord substr $str, $_, 1 ) * $v1 / $v2 for 0 .. length( $str ) -1; return $result; } our $T //= 4; our $N //= 100; my $step = int( $N / $T ); my $now = time; my $total :shared = 0; my $str = 'the quick brown fox jumps over the lazy dog' x 100; my( $start, $end ) = ( 0, $step ); my @threads = map{ my $thread = async{ for my $v1 ( $start .. $end ) { for my $v2 ( 1 .. $N ) { lock $total; ## Lock $total += x( $str, $v1, $v2 ); ## update } } }; $start += $step +1; $end = $start + $step < $N ? $start + $step : $N; $thread; } 1 .. $T; $_->join for @threads; printf STDERR "With $T threads took %.6f seconds\n", time() - $now; print $total; __END__ c:\test>859242-2 -T=1 -N=100 With 1 threads took 14.250000 seconds 10711649268.1623 c:\test>859242-2 -T=2 -N=100 With 2 threads took 14.297000 seconds 10711649268.1623 c:\test>859242-2 -T=3 -N=100 With 3 threads took 14.476000 seconds 10711649268.1623 c:\test>859242-2 -T=4 -N=100 With 4 threads took 14.536000 seconds 10711649268.1623