public
Last active

event vs. non-event approach for writing to a child

  • Download Gist
event.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#!/usr/bin/env perl
 
use strict;
use warnings;
use feature ':5.10';
 
use AnyEvent;
use AnyEvent::Handle;
 
open my $fd, '|-', 'perl -ne "sleep 1; print"' or die $!;
 
my $done = AnyEvent->condvar;
my $h = AnyEvent::Handle->new( fh => $fd );
 
for(1..100){
warn $_;
$h->push_write("$_"x100000);
$h->push_write("\n");
sleep 1 if $_ % 10 == 0; # lets you observe that some writes take place before the end of the loop
}
warn "wait for writes";
$h->on_drain(sub { $done->send });
$done->wait;
warn "bye";
 
# the slow child never blocks the parent's main loop; all blocking happens right before exit
nonevent.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#!/usr/bin/env perl
 
use strict;
use warnings;
use feature ':5.10';
 
 
open my $fd, '|-', 'perl -ne "sleep 1; print"' or die $!;
 
for(1..100){
warn $_;
print $fd "$_"x100000;
print $fd "\n";
}
 
warn "bye";
 
# slow child blocks the parent's for loop

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.