docs
[mirrors/Programs.git] / perl / prime.pl
1 #!/usr/bin/perl
2 # prime-pthread, courtesy of Tom Christiansen
3
4 use strict;
5 use warnings;
6
7 use threads;
8 use Thread::Queue;
9
10 my $stream = Thread::Queue->new();
11 for my $i ( 3 .. 1000 ) {
12 $stream->enqueue($i);
13 }
14 $stream->enqueue(undef);
15
16 threads->create(\&check_num, $stream, 2);
17 $kid->join();
18
19 sub check_num {
20 my ($upstream, $cur_prime) = @_;
21 my $kid;
22 my $downstream = Thread::Queue->new();
23 while (my $num = $upstream->dequeue()) {
24 next unless ($num % $cur_prime);
25 if ($kid) {
26 $downstream->enqueue($num);
27 } else {
28 print("Found prime $num\n");
29 $kid = threads->create(\&check_num, $downstream, $num);
30 }
31 }
32 if ($kid) {
33 $downstream->enqueue(undef);
34 $kid->join();
35 }
36 }
This page took 0.289386 seconds and 4 git commands to generate.