You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Fan-In is a messaging pattern used to create a funnel for work amongst workers (clients: source, server: destination).
4
+
5
+
We can model fan-in using the Go channels.
6
+
7
+
```go
8
+
// Merge different channels in one channel
9
+
funcMerge(cs ...<-chanint) <-chanint {
10
+
varwg sync.WaitGroup
11
+
12
+
out:=make(chanint)
13
+
14
+
// Start an send goroutine for each input channel in cs. send
15
+
// copies values from c to out until c is closed, then calls wg.Done.
16
+
send:=func(c <-chanint) {
17
+
forn:=range c {
18
+
out <- n
19
+
}
20
+
wg.Done()
21
+
}
22
+
23
+
wg.Add(len(cs))
24
+
for_, c:=range cs {
25
+
gosend(c)
26
+
}
27
+
28
+
// Start a goroutine to close out once all the send goroutines are
29
+
// done. This must start after the wg.Add call.
30
+
gofunc() {
31
+
wg.Wait()
32
+
close(out)
33
+
}()
34
+
return out
35
+
}
36
+
```
37
+
38
+
The `Merge` function converts a list of channels to a single channel by starting a goroutine for each inbound channel that copies the values to the sole outbound channel.
39
+
40
+
Once all the output goroutines have been started, `Merge` a goroutine is started to close the main channel.
0 commit comments