Skip to content

Instantly share code, notes, and snippets.

@tk3369
Created May 10, 2020 00:30
Show Gist options
  • Save tk3369/1766c24826596d4bc27dd098269c4940 to your computer and use it in GitHub Desktop.
Save tk3369/1766c24826596d4bc27dd098269c4940 to your computer and use it in GitHub Desktop.
Composing with channels
# 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