Created
December 13, 2016 03:32
-
-
Save DougEverly/ab32c3fa1fa4552a2317cc417706889c 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
| enum Control | |
| Done | |
| end | |
| class Worker(T) | |
| def initialize | |
| @channel = Channel(T|Control).new(10) | |
| @done = Channel(Control).new | |
| end | |
| def add(item : T) | |
| @channel.send(item) | |
| end | |
| def run | |
| spawn { | |
| loop do | |
| item = @channel.receive | |
| case item | |
| when T | |
| puts "I got #{item}" | |
| when Control | |
| @done.send(item) | |
| break | |
| end | |
| end | |
| } | |
| end | |
| def done | |
| @channel.send(Control::Done) | |
| end | |
| def join | |
| puts "waiting" | |
| @done.receive | |
| end | |
| end | |
| w = Worker(Int32).new | |
| w.run | |
| w.add 2 | |
| w.add 1 | |
| w.add 3 | |
| w.done | |
| w.join | |
| puts "Done" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment