Skip to content

Instantly share code, notes, and snippets.

@waffle2k
Created December 11, 2009 16:29
Show Gist options
  • Save waffle2k/254314 to your computer and use it in GitHub Desktop.
Save waffle2k/254314 to your computer and use it in GitHub Desktop.
#!/usr/bin/perl
use threads;
use Thread::Queue;
my $TC = 50; # Thread Count
my $q = new Thread::Queue;
my $q_print = new Thread::Queue;
# Read all of the input work
while (<>) {
chomp;
$q->enqueue($_);
}
# Create the printer thread
my ($q_print_thread) = threads->create(print_work);
# Create the threads
my @threads = ();
for ( 1 .. $TC ) {
my ($thread) = threads->create(thread_work);
push( @threads, $thread );
$q->enqueue( undef ); # Send a quit message to the thread
}
# Wait for the worker threads to finish
foreach my $thread (@threads) {
$thread->join();
}
# Sent a undef to terminate the printer
$q_print->enqueue(undef);
$q_print_thread->join();
exit(0);
##############################################################################
sub thread_work {
# Do some kind of per-thread initialization that
# is required in context of this thread
# Pull work from the queue
while ( my $line = $q->dequeue_nb ) {
return if !$line; # This tells us that there's no more work
# Insert work here
# Post results here
$q_print->enqueue( "Some kind of results" );
}
}
sub print_work {
while ( my $line = $q_print->dequeue() ) {
return if !$line;
print "$line\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment