zentara, thanks for yet another great worker thread example. ++. I'm pretty sure you know the techniques I use below. I hope that my alternate, goto-less approach is useful to someone.
It's possible to get rid of the gotos. I don't know that it improves readability/maintainability. I like the way that the gotos work to jump out of the loop in the original.
On with the code. Removing the first goto:
PROCESS_DATA:
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"; last PROCESS_DATA; }
}
} # end PROCESS_DATA
I used last to break out of the loop. I added a label to retain the readability of the goto version. It's functionally equivalent to the goto version.
Now the second and third goto:
sub worker{
my $thr_num = shift;
print "$thr_num started\n";
my $count;
while(1) {
WORKER_LOOP:
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){ last WORKER_LOOP; }
#select(undef,undef,undef,.25);
sleep rand 5
}else{
$count = 0;
select(undef,undef,undef,.25);
}# sleep until awakened
} #end WORKER_LOOP
# Recycle Thread
$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";
}
return;
}
I wrapped the section bracketed by the START label and goto START with a loop. I didn't label the loop, because we never break it. It may make sense to apply a label here in some instances.
I added a label to the pre-existing loop (now an inner loop), and use last to break out of it as needed. Once again, to improve readability, I used a label where it isn't necessary.
Whether these changes are worth making, I can't say for sure. I tend to prefer the inner/outer loop arrangement I show above to zentara's loop implemented as a goto, simply because I can bounce between the enclosing brackets with my % key. I like the other gotos, and feel that they do help readability. YMMV.
|