in reply to Reusable threads demo

Hi zentara,

Found this thread via your mention of it here. I'm providing a demonstration for Perl lacking threads support. Perl with threads support may run MCE::Shared as well. Simply replace MCE::Hobo with threads. I went completely OO with the shared objects for minimum overhead.

#!/usr/bin/perl use strict; use warnings; use MCE::Hobo; use MCE::Shared; my %shash; my @to_be_processed = ('a'..'z'); my $ready = MCE::Shared->array; my $numworkers = 10; foreach my $dthread(1..$numworkers){ $shash{$dthread}{'go'} = MCE::Shared->scalar( 0); $shash{$dthread}{'fileno'} = MCE::Shared->scalar(''); #in case you want shared filehandles $shash{$dthread}{'data'} = MCE::Shared->scalar(''); $shash{$dthread}{'pid'} = MCE::Shared->scalar(-1); $shash{$dthread}{'die'} = MCE::Shared->scalar( 0); $shash{$dthread}{'thread'} = MCE::Hobo->new(\&worker, $dthread); $ready->push($dthread); } print "\t\t",$ready->len," threads ready.......press a key to start th +reads\n"; <>; while (my $t = $ready->shift){ $shash{$t}{'data'}->set(shift @to_be_processed); $shash{$t}{'go'}->set(1); } while(1){ if( $ready->len > 0 ){ if( my $data = shift @to_be_processed ){ my $t = $ready->shift; $shash{$t}{'data'}->set($data); $shash{$t}{'go'}->set(1); print "thread $t restarting\n"; }else{ print "out of input\n"; goto WAIT; } } } WAIT: print "\n\n\nWAITING FOR FINISH\n\n\n"; while(1){ print "\n\n\n",$ready->len," are ready\n\n\n"; if( $ready->len < $numworkers ){ sleep 1; }else{ foreach my $t ( $ready->vals ){ $shash{$t}{'die'}->set(1); $shash{$t}{'thread'}->join; print "joining thread $t\n"; } exit; } } sub worker{ my $thr_num = shift; print "$thr_num started\n"; #create your reusable objects here if needed my $count; START: while(1){ if( $shash{$thr_num}{'die'}->get() ){ print "thread $thr_num finishing\n"; return } #wait for $go_control if( $shash{$thr_num}{'go'}->get() ){ if( $shash{$thr_num}{'die'}->get() ){ print "thread finishing\n"; return } $count++; my $str = ' 'x$thr_num; #printout spacer print $str.$thr_num.'->'.$count.$shash{$thr_num}{'data'}-> +get(),"\n"; if( $count > 10 ){ goto RECYCLE; } #select(undef,undef,undef,.25); sleep rand 5 }else{ $count = 0; select(undef,undef,undef,.25); } #sleep until awakened } #end while(1) RECYCLE: $shash{$thr_num}{'go'}->set(0); print "$thr_num done....going back to sleep\n"; $shash{$thr_num}{'data'}->set(''); #clean out temp data from objects here, if needed #see "perldoc -q clear" $count = 0; $ready->push($thr_num); print "pushing $thr_num\n"; goto START; return; }

Regards, Mario

Replies are listed 'Best First'.
Re^2: Reusable threads demo
by zentara (Cardinal) on May 11, 2018 at 12:08 UTC
    Another nice example for the MCE::Hobo Cookbook. :-) Thanks.

    I'm not really a human, but I play one on earth. ..... an animated JAPH