#!/usr/bin/perl $|=1; use strict; use warnings; use threads; use threads::shared; use Data::Dumper; # Global vars # Maximum working threads my $MAX_THREADS = 20; # Flag to inform all threads that application is terminating my $TERM:shared=0; # Prevents double detach attempts my $DETACHING:shared; # Signal handling $SIG{'INT'} = $SIG{'TERM'} = sub { print("^C captured\n"); $TERM=1; }; # thread sub stuff_thr($) { my ($job)=@_; # My thread ID my $tid=threads->tid(); # do some thread stuff print "Hi, I am thread: $tid, I need to do something with $job\n"; # Detach and terminate { lock($DETACHING); threads->detach() if ! threads->is_detached(); } return(0); } # main sub main() { # Manage the thread pool until we run out of data or signalled # to terminate my @jobs=(1..100); while (@jobs && ! $TERM) { # Keep max threads running for (my $needed = $MAX_THREADS - threads->list(); $needed && ! $TERM; $needed--) { my $job = shift(@jobs); last if (! $job); # New thread threads->create('stuff_thr',$job); } # normally fetch a limited amount of data from a db to # process, at this point just make sure the job queue # is never empty if(scalar(@jobs) < 10) { @jobs=(1..100); } } while ((threads->list() > 0)) { # waiting for threads to finish sleep(1); } } # enter main() main();