ithreads
:
$ perl -MConfig -e 'print "$Config{useithreads}\n"' defineEl área bajo la curva entre 0 y nos proporciona un método para calcular :
$ cat -n pi.pl 1 #!/usr/bin/perl -w 2 # el número Pi es 3. 3 # 1415926535 8979323846 2643383279 5028841971 6939937510 5820974944 5923078164 4 # 0628620899 8628034825 3421170679 8214808651 3282306647 0938446095 5058223172 5 # 5359408128 4811174502 8410270193 8521105559 6446229489 5493038196 4428810975 6 # 6659334461 2847564823 3786783165 2712019091 4564856692 3460348610 4543266482 7 # 1339360726 0249141273 7245870066 0631558817 4881520920 9628292540 9171536436 8 9 use strict; 10 use threads; 11 use threads::shared; 12 13 our $N; 14 our $numthreads; 15 our $pi = 0; 16 17 sub chunk { 18 my $N = shift; 19 my $numthreads = shift; 20 21 my ($i, $x, $sum, $w); 22 my $id = threads->self()->tid(); 23 $w = 1/$N; 24 $sum = 0; 25 for ($i = $id; $i < $N; $i += $numthreads) { 26 $x = ($i + 0.5)*$w; 27 $sum += 4.0/(1.0 + $x*$x); 28 } 29 print "thread $id: $sum\n"; 30 return $sum; 31 } 32 33 sub par { 34 my $nt = shift(); 35 my $task = shift; 36 my @t; # array of tasks 37 my $i; 38 my @results; 39 40 for($i=1; $i < $nt; $i++) { 41 $t[$i] = threads->new($task, @_); 42 } 43 @{$results[0]} = $task->( @_); 44 for($i=1; $i < $nt; $i++) { 45 @{$results[$i]} = $t[$i]->join(); 46 } 47 @results; 48 } 49 50 ### main ### 51 $numthreads = (shift || 2); 52 $N = (shift || 10000); 53 54 my @results = par($numthreads, \&chunk, $N, $numthreads); 55 for (@results) { $pi += $_->[0] } 56 $pi /= $N; 57 58 print "PI = $pi\n"; 59 for (@results) { 60 print @$_," "; 61 } 62 print "\n";Ejecución:
$ time ./pi.pl 1 1000000 thread 0: 3141592.65358976 PI = 3.14159265358976 3141592.65358976 real 0m0.976s user 0m0.960s sys 0m0.010s $ time ./pi.pl 2 1000000 thread 1: 1570795.82679499 thread 0: 1570796.82679495 PI = 3.14159265358994 1570796.82679495 1570795.82679499 real 0m0.584s user 0m1.080s sys 0m0.000sLa máquina:
$ perl -ne 'print if m/processor|model_name|cache|MHz/' /proc/cpuinfo processor : 0 cpu MHz : 2657.850 cache size : 512 KB processor : 1 cpu MHz : 2657.850 cache size : 512 KB processor : 2 cpu MHz : 2657.850 cache size : 512 KB processor : 3 cpu MHz : 2657.850 cache size : 512 KBRealmente en la máquina usada sólo hay dos procesadores, cada uno de los cuales virtualiza dos procesadores.
parfor
que implante este tipo de asignación.
Vea también perldoc perlthrtut
o bien
http://search.cpan.org/~nwclark/perl-5.8.6/pod/perlthrtut.pod
Casiano Rodríguez León