Skip to content

Instantly share code, notes, and snippets.

@TristinDavis
Forked from kentfredric/gist:4092780
Created February 14, 2013 16:08
Show Gist options
  • Save TristinDavis/4953819 to your computer and use it in GitHub Desktop.
Save TristinDavis/4953819 to your computer and use it in GitHub Desktop.
use strict;
use warnings;
use IO::Async::Channel;
use IO::Async::Loop;
use IO::Async::Routine;
my $loop = IO::Async::Loop->new();
{
package Slave;
use parent 'IO::Async::Routine';
sub configure {
my $self = shift;
my %params = @_;
$self->{controlstream} = IO::Async::Channel->new(
on_recv => sub {
my ( $channel, $data ) = @_;
my $event = delete $data->{event};
if ( exists $self->{events}->{$event} ) {
return $self->{events}->{$event}->($data);
}
warn "Unhanlded event << $event >>\n";
}
);
$self->{loop_setup} = delete $params{loop_setup};
$self->{events} = delete $params{events};
$self->{events} //= {};
$self->SUPER::configure(
%params,
channels_in => [ $self->{controlstream} ],
channels_out => [],
code => sub {
$self->run();
},
);
}
sub _add_to_loop {
my $self = shift;
if ( exists $self->{loop_setup} ) {
$self->{loop_setup}->( $self, @_ );
}
$self->SUPER::_add_to_loop(@_);
}
sub do_event {
my ( $self, $event, @args ) = @_;
my $message = {
event => $event,
args => \@args
};
$self->{controlstream}->send($message);
}
sub on_finish {
warn "Got exit condition before the exit signal\n";
$loop->stop();
}
}
my $slave = Slave->new(
setup => sub {
my ( $self, $loop ) = @_;
},
events => {
'hello' => sub { STDERR->say("Got HELLO in slave"); },
'exit' => sub { STDERR->say("Got EXIT in slave"); },
},
);
$loop->add($slave);
$slave->do_event( hello => {} );
$slave->do_event( exit => {} );
$loop->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment