Skip to content

Instantly share code, notes, and snippets.

@jnthn
Last active January 18, 2016 21:56
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 jnthn/03e01cba53418c1f0f3c to your computer and use it in GitHub Desktop.
Save jnthn/03e01cba53418c1f0f3c to your computer and use it in GitHub Desktop.
class BoundedChannel is Channel {
has $!lock = Lock.new;
has $!send-cond = $!lock.condition;
has $.limit is required;
method send(|c) {
$!lock.lock();
LEAVE $!lock.unlock();
while $!limit == 0 {
$!send-cond.wait();
}
$!limit--;
nextsame();
}
method receive() {
my \got = callsame();
self!received();
got
}
method poll() {
my \got = callsame();
unless got === Nil {
self!received();
}
got
}
method !received() {
$!lock.lock();
LEAVE $!lock.unlock();
$!limit++;
if $!limit == 1 {
$!send-cond.signal();
}
}
}
my $bc = BoundedChannel.new(limit => 5);
start {
loop {
say "Got $bc.receive()";
sleep 1;
}
CATCH { say $_ }
}
for 1..* {
say "Sending $_";
$bc.send($_);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment