Last active
December 12, 2018 13:12
-
-
Save m-dango/2d857d9b2b559bd303e353bd49429365 to your computer and use it in GitHub Desktop.
Internet Café Concurrency Exercise in Perl 6
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
# 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