Skip to content

Instantly share code, notes, and snippets.

@jrockway
Created June 9, 2009 13:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrockway/126488 to your computer and use it in GitHub Desktop.
Save jrockway/126488 to your computer and use it in GitHub Desktop.
event vs. non-event approach for writing to a child
#!/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
#!/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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment