Skip to content

Instantly share code, notes, and snippets.

@kanatohodets
Created February 13, 2015 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanatohodets/66978923c5006b45a67b to your computer and use it in GitHub Desktop.
Save kanatohodets/66978923c5006b45a67b to your computer and use it in GitHub Desktop.
p5 workerpool
use v6;
use Inline::Perl5;
use OO::Monitors;
class P5Worker {
has $!id;
has $!p5;
has $!owner;
method run($code) {
say "I am worker $!id running some code: $code";
my $ret = $!p5.run($code);
$!owner.check-in(self);
return $ret;
}
submethod BUILD(:$!id, :$!owner, :$!p5 = Inline::Perl5.new) { }
}
# nooooo! the abstract beans are coming!
# (WorkerPoolFactory was the first name for this class)
class WorkerPool {
monitor BlockingPool is conditioned(<available-interpreter>) {
has @.workers;
has $!size = 4;
method check-out($work-id) {
until @.workers {
say "there are no interpreters available?? $work-id";
wait-condition <available-interpreter>;
}
return @.workers.shift;
}
method check-in(P5Worker $interpreter) {
@.workers.push($interpreter);
meet-condition <available-interpreter>;
}
}
method create(:$size = 4) {
my $wp = BlockingPool.new();
# we need this factory class because monitors can't have "new" or "BUILD" methods just yet
for (^$size) -> $i {
my $p5 = P5Worker.new( id => $i, owner => $wp);
$wp.workers.push($p5);
}
return $wp;
}
}
my $wp = WorkerPool.create(size => 10);
my $start-work = now;
await do for (^10) -> $i {
start {
my $p5 = $wp.check-out($i);
my $ret = $p5.run("sleep 1; return 'hi $i'");
say $ret;
}
}
say "threaded work took: ", now - $start-work;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment