Created
May 10, 2020 00:30
-
-
Save tk3369/1766c24826596d4bc27dd098269c4940 to your computer and use it in GitHub Desktop.
Composing with channels
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
# sum worker | |
function sum_worker(source) | |
target = Channel() | |
task = @async while true | |
args = take!(source) | |
args === nothing && break | |
result = sum(args) | |
push!(target, result) | |
end | |
return (output = target, task = task) | |
end | |
# Fan-out. Take 1 msg from channel and distribute to N other channels. | |
function fanout(source; n = 1) | |
targets = [Channel() for i in 1:n] | |
task = @async while true | |
msg = take!(source) | |
args === nothing && break | |
foreach(target -> push!(target, msg), targets) | |
end | |
return (output = targets, task = task) | |
end | |
source = Channel() | |
harness = sum_worker(source) # this is async | |
while true # test worker | |
println(take!(harness.output)) | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment