Created
March 13, 2013 17:13
-
-
Save skaji/5154193 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env perl | |
use strict; | |
use warnings; | |
use utf8; | |
use 5.010; | |
my $app = App->new; | |
$app->stash( data => [1..100] ); | |
$app->register(sub { | |
my ($pid, $stash) = @_; | |
map { say join ' ', $pid, $_, $stash->{data}[0]; sleep 1 } 0..9; | |
}); | |
$app->register(sub { | |
my ($pid, $stash) = @_; | |
map { say join ' ', $pid, $_, $stash->{data}[1]; sleep 1 } 0..9; | |
}); | |
$app->register(sub { | |
my ($pid, $stash) = @_; | |
map { say join ' ', $pid, $_, $stash->{data}[2]; sleep 1 } 0..9; | |
}); | |
$app->start; | |
package App; | |
use strict; | |
use warnings; | |
sub new { | |
my $class = shift; | |
bless { process => [], stash => {}, pid => [] }, $class; | |
} | |
sub stash { | |
my $self = shift; | |
if (ref $_[0] eq 'HASH') { | |
$self->{stash}{$_} = $_[0]{$_} for keys %{ $_[0] }; | |
} | |
else { | |
$self->{stash}{$_[0]} = $_[1]; | |
} | |
} | |
sub register { | |
my ($self, $cb) = @_; | |
push @{ $self->{process} }, $cb; | |
} | |
sub start { | |
my $self = shift; | |
for my $i (0..$#{ $self->{process} }) { | |
my $pid = fork; | |
if ($pid) { | |
push @{ $self->{pid} }, $pid; | |
next; | |
} | |
die if !defined $pid; | |
$self->{process}[$i]($$, $self->{stash}); | |
exit; | |
} | |
waitpid $_, 0 for @{ $self->{pid} }; | |
} | |
1; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment