Skip to content

Instantly share code, notes, and snippets.

@m-dango
Last active December 12, 2018 13:12
Show Gist options
  • Save m-dango/2d857d9b2b559bd303e353bd49429365 to your computer and use it in GitHub Desktop.
Save m-dango/2d857d9b2b559bd303e353bd49429365 to your computer and use it in GitHub Desktop.
Internet Café Concurrency Exercise in Perl 6
# http://whipperstacker.com/2015/10/05/3-trivial-concurrency-exercises-for-the-confused-newbie-gopher/
unit sub MAIN (
UInt :$tourists where * > 0 = 25,
UInt :$computers where * > 0 = 8,
);
my @computers is Channel;
@computers.send(++$) xx $computers;
loop {
state @queue = pick *, 1..$tourists;
once @queue.say;
given @computers.poll {
when Nil|@queue.not {
say “Tourist $_ waiting for turn.” for @queue;
last;
}
default {.&use-computer: @queue.shift}
}
LAST {
given @queue {
use-computer @computers.receive, .shift while .elems
}
}
}
sub use-computer ($computer, $tourist) {
state @promises;
say “{:$tourist.kv.join(‘ ’).tc} is on {:$computer.kv.join: ‘ ’}.”;
given (15..120).rand.round -> $time {
@promises.push(Promise.in($time ÷ 20).then: {
say “{:$tourist.kv.join(‘ ’).tc} is done, having spent $time minutes on {:$computer.kv.join: ‘ ’}.”;
@computers.send: $computer;
});
}
END {
if @promises {
await Promise.allof: @promises;
say ‘The place is empty, let's close up and go to the beach!’;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment