#! perl -slw
# Parallel example for Perl not built with threads support.
# Based on https://www.perlmonks.org/?node_id=897591.
use strict;
use Time::HiRes qw[ time usleep ];
use MCE::Hobo;
use MCE::Shared;
use IO::Socket;
our $port //= 12345;
my $condvar = MCE::Shared->condvar;
my $svrN = MCE::Shared->scalar( 0 );
my $clientN = MCE::Shared->scalar( 0 );
my $is_winenv = ( $^O =~ /mswin|mingw|msys|cygwin/i );
my $start = time;
mce_async {
my $svr = IO::Socket::INET->new(
Listen => SOMAXCONN,
Reuse =>1,
LocalPort => $port,
Timeout => 0.1,
) or die $!;
# signal the client ready
$condvar->signal;
while( my $client = $svr->accept ) {
my $in = <$client>;
print $client "echod:$in";
syswrite($client, '0') if $is_winenv;
$client->shutdown( 2 );
close $client;
$svrN->incr;
}
};
mce_async {
# wait for the server connection
$condvar->wait;
while( 1 ) {
my $svr = IO::Socket::INET->new(
PeerHost => 'localhost',
PeerPort => $port,
Reuse => 1,
Timeout => 0.1,
) or usleep( 10_000 ), next;
sleep 0;
print $svr $clientN->incr;
my $echo = <$svr>;
sleep 0;
syswrite($svr, '0') if $is_winenv;
$svr->shutdown( 2 );
close $svr;
sleep 0;
}
};
$|++;
while( usleep 100_000 ) {
my ( $n1, $n2 ) = ( $svrN->get, $clientN->get );
printf "\rserver:$n1 client:$n2 cycles: %.3f/sec",
$n1 / ( time() - $start );
}
####
Y:\>perl demo_thr.pl
server:29889 client:29889 cycles: 2119.429/secTerminating on signal SIGINT(2)
Y:\>perl demo_mce.pl
server:35619 client:35620 cycles: 1771.711/secTerminating on signal SIGINT(2)
####
$ perl demo_thr.pl
server:31879 client:31879 cycles: 2128.663/sec
$ perl demo_mce.pl
server:31690 client:31691 cycles: 1856.834/sec