#!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; use POSIX; # on linux, watch with "ps -T uxww" to see threads # daemonize if(1) { exit if fork; POSIX::setsid(); } # script goes here open (FH,">$0.out")or die "$!\n"; #prints go to FH select(*FH); $| = 1; # Turn on autoflush for FH my %shash; my @to_be_processed = ('a'..'z'); my @ready:shared = (); my $numworkers = 10; foreach my $dthread(1..$numworkers){ share $shash{$dthread}{'go'}; $shash{$dthread}{'go'} = 0; share $shash{$dthread}{'fileno'}; #in case you want $shash{$dthread}{'fileno'} = ''; #shared filehandles share $shash{$dthread}{'data'}; $shash{$dthread}{'data'} = ''; share $shash{$dthread}{'pid'}; $shash{$dthread}{'pid'} = -1; share $shash{$dthread}{'die'}; $shash{$dthread}{'die'} = 0; $shash{$dthread}{'thread'} = threads->new(\&worker, $dthread); push @ready, $dthread; } #print "\t\t",scalar @ready," threads ready.......press a key to start threads\n"; #<>; RUN: print FH "Running again\n"; @to_be_processed = ('a'..'z'); #reload fake data while (my $t = shift(@ready)){ $shash{$t}{'data'} = shift @to_be_processed; $shash{$t}{'go'} = 1; } while(1){ if( scalar @ready > 0 ){ if( my $data = shift @to_be_processed ){ my $t = shift(@ready); $shash{$t}{'data'} = $data; $shash{$t}{'go'} = 1; #print "thread $t restarting\n"; }else{ print "out of input\n"; goto WAIT; } } } WAIT: #print "at end loop\n"; print FH "sleeping\n"; for(1..10){ sleep(1) } print "restarting another run\n"; goto RUN; ###############################################3 sub worker{ my $thr_num = shift; #print "$thr_num started\n"; my $count; START: while(1){ if( $shash{$thr_num}{'die'} ){ #print "thread $thr_num finishing\n"; return} #wait for $go_control if($shash{$thr_num}{'go'}){ if($shash{$thr_num}{'die'}){ #print "thread finishing\n"; return} $count++; my $str = ' 'x$thr_num; #printout spacer #print $str.$thr_num.'->'.$count.$shash{$thr_num}{'data'},"\n"; if ($count > 10){ goto RECYCLE; } select(undef,undef,undef,.1); #sleep rand 5 }else{ $count = 0; select(undef,undef,undef,.1); }# sleep until awakened } #end while(1) RECYCLE: $shash{$thr_num}{'go'} = 0; #print "$thr_num done....going back to sleep\n"; $shash{$thr_num}{'data'} = ''; $count = 0; push @ready, $thr_num; #print "pushing $thr_num\n"; goto START; return; }