2008/07/25

The Labs.Com Issue_10_Threads
Last update 1999/02/20

TPJ: Issue_10_Threads

This is a collection of programs published by The Perl Journal. You can download all source-code also from TPJ: Programs.
  1. primes
  2. primes~
  3. More Samples on Threads
Issue_10_Threads
1. primes
Download primes

 #!/usr/bin/perl -w 
 # prime-pthread, courtesy of Tom Christiansen 
  
 use strict; 
 use Thread; 
 use Thread::Queue; 
  
 my $stream = new Thread::Queue; 
 my $kid    = new Thread(\&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; 
     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"; 
             $kid = new Thread(\&check_num, $downstream, $num); 
         } 
     }  
     $downstream->enqueue(undef) if $kid; 
     $kid->join()                if $kid; 
 } 

Issue_10_Threads
2. primes~

Download primes~

  #!/usr/bin/perl -w 
  # prime-pthread, courtesy of Tom Christiansen 
  use strict; 
  use Thread; 
  use Thread::Queue; 
  my $stream = new Thread::Queue; 
 my $kid    = new Thread(\&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; 
     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"; 
      $kid = new Thread(\&check_num, $downstream, $num); 
  } 
     }  
     $downstream->enqueue(undef) if $kid; 
     $kid->join()                if $kid; 
 } 

Issue_10_Threads
3. More Samples on Threads

  • Issue_10_Threads

                                                                                                                                   

Last update 1999/02/20

All Rights Reserved - (C) 1997 - 2008 by The Labs.Com

Top of Page

The Labs.Com