Last active
January 18, 2016 21:56
-
-
Save jnthn/03e01cba53418c1f0f3c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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