$ cat -n primes-without-threads.pl
1 #!/usr/bin/perl -w
2 use strict;
3
4 my @primes = (2);
5
6 NEW_NUMBER:
7 for my $num (3 .. 1000) {
8 foreach (@primes) { next NEW_NUMBER if $num % $_ == 0 }
9 print "Found prime $num\n";
10 push @primes, $num;
11 }
Paralelo:
$ cat -n primes-using-threads.pl
1 #!/usr/bin/perl -w
2
3 use strict;
4
5 use threads;
6 use Thread::Queue;
7
8 my $stream = new Thread::Queue;
9 my $kid = new threads(\&check_num, $stream, 2);
10
11 for my $i (3 .. 1000) {
12 $stream->enqueue($i);
13 }
14
15 $stream->enqueue(undef);
16 $kid->join;
17
18 sub check_num {
19 my ($upstream, $cur_prime) = @_;
20 my $kid = undef;
21 my $downstream = new Thread::Queue;
22 while (my $num = $upstream->dequeue) {
23 next unless $num % $cur_prime;
24 if ($kid) {
25 $downstream->enqueue($num);
26 } else {
27 print "Found prime $num\n";
28 $kid = new threads(\&check_num, $downstream, $num);
29 }
30 }
31 $downstream->enqueue(undef) if $kid;
32 $kid->join if $kid;
33 }
Casiano Rodríguez León
