#!/usr/bin/perl

##use threads;

print "Hello, World...\n";

# threads->new(\&thread_sub, @sub_params)
#my $child_thread = threads->new(\&my_function);
#my @returned_data = $child_thread->join;
#print "Child thread returned [", join( ' ', @returned_data), "]\n";
#sub my_function { return ("Israel PM", 2003, "September", 11); }

my @primes = (2);
#NEW_NUMBER:
#for my $num (3 .. 1000) {
#	foreach (@primes) { next NEW_NUMBER if $num % $_ == 0 }
#	print "Found prime $num\n";
#	push @primes, $num;
#}

use threads;
use Thread::Queue;

my $stream = new Thread::Queue;
my $kid    = new threads(\&check_num, $stream, 2);

for my $i (3 .. 1000) {
	$stream->enqueue($i);
}

$stream->enqueue(undef);
$kid->join;

sub check_num {
	my ($upstream, $cur_prime) = @_;
	my $kid = undef;
	my $downstream = new Thread::Queue;
	while (my $num = $upstream->dequeue) {
		next unless $num % $cur_prime;
		if ($kid) {
			$downstream->enqueue($num);
		} else {
			print "Found prime $num\n";
			push @primes, $num;
			$kid = new threads(\&check_num, $downstream, $num);
		}
	}
	$downstream->enqueue(undef) if $kid;
	$kid->join if $kid;
}

#eof
