-
-
Save kanatohodets/66978923c5006b45a67b to your computer and use it in GitHub Desktop.
p5 workerpool
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
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