The demo scripts are based on the one found here. One makes use of MCE::Hobo + Inbox2. The other utilizing threads + Inbox4.
$ diff hobo_demo.pl threads_demo.pl
5,6c5,6
< use MCE::Hobo;
< use Foo::Inbox2;
---
> use threads;
> use Foo::Inbox4;
10c10
< my $inbox = Foo::Inbox2->new( @names );
---
> my $inbox = Foo::Inbox4->new( @names );
34c34
< MCE::Hobo->create(\&foo, $_) for @names;
---
> threads->create(\&foo, $_) for @names;
44c44
< MCE::Hobo->waitall;
---
> $_->join() for threads->list();
Foo::Inbox2 via MCE::Hobo + MCE::Shared->queue example
use strict;
use warnings;
use MCE::Hobo;
use Foo::Inbox2;
use List::Util 'shuffle';
my @names = shuffle qw/ Barny Betty Fred Wilma /;
my $inbox = Foo::Inbox2->new( @names );
my $index = 0;
$| = 1;
sub foo {
my $name = shift;
my $count = 0;
# remove my name from the list
@names = grep { $_ ne $name } shuffle @names;
# send greeting to names on the list
$inbox->send($name, \@names, 'Hello');
while ( my ($from, $data) = $inbox->recv($name) ) {
printf "%-5s received %s from %s\n", $name, $data->[0], $from;
# forward the message to another worker
$inbox->send($name, $names[ ++$index % @names ], $data->[0])
if ( $from eq 'manager' );
}
}
MCE::Hobo->create(\&foo, $_) for @names;
# Enter message or type quit to terminate the script.
while ( my $msg = <STDIN> ) {
chomp $msg; next unless ( length $msg );
$inbox->end(), last() if ( $msg eq 'quit' );
$inbox->send('manager', $names[ ++$index % @names ], $msg);
}
MCE::Hobo->waitall;
Foo::Inbox4 via threads + Thread::Queue example
use strict;
use warnings;
use threads;
use Foo::Inbox4;
use List::Util 'shuffle';
my @names = shuffle qw/ Barny Betty Fred Wilma /;
my $inbox = Foo::Inbox4->new( @names );
my $index = 0;
$| = 1;
sub foo {
my $name = shift;
my $count = 0;
# remove my name from the list
@names = grep { $_ ne $name } shuffle @names;
# send greeting to names on the list
$inbox->send($name, \@names, 'Hello');
while ( my ($from, $data) = $inbox->recv($name) ) {
printf "%-5s received %s from %s\n", $name, $data->[0], $from;
# forward the message to another worker
$inbox->send($name, $names[ ++$index % @names ], $data->[0])
if ( $from eq 'manager' );
}
}
threads->create(\&foo, $_) for @names;
# Enter message or type quit to terminate the script.
while ( my $msg = <STDIN> ) {
chomp $msg; next unless ( length $msg );
$inbox->end(), last() if ( $msg eq 'quit' );
$inbox->send('manager', $names[ ++$index % @names ], $msg);
}
$_->join() for threads->list();
Regards, Mario