Skip to content

Instantly share code, notes, and snippets.

@jnthn
Last active Jan 18, 2016
Embed
What would you like to do?
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