Go Concurrency Patterns: Fan-In
It is not uncommon to have a piece of software that is concurrently reading from multiple streams of data. However, for a multitude of possible reasons, we might want to aggregate these streams into a single one, for example, to send the data to another service. Fortunately, this is not a new problem, and the solution for it is well known as the Fan-In pattern.
The Fan-In pattern in Go
As stated before, the idea behind this is incredibly simple: the fan-in pattern combines several data streams into one. You’ve possibly seen this defined in terms of “multiplexing”. Fret not, that is just a fancy word for “merging multiple streams into one”. There is nothing like learning by doing, so let us get right to it.
The first thing we need is to emulate multiple streams of data. For that matter, I created two functions someNumberStrings
and someNumbers
which both spawn a goroutine and return a channel to where the aforementioned goroutine will write some strings:
|
|
Before diving into the code for multiplexing these data streams, let us think about what we need. The two data streams will be combined into one, so we need to create a new channel, which will be our multiplexed channel (or stream). Then, we’ll need a function, multiplex
, that reads from the two channels and writes to our multiplexed channel. Since we are writing concurrently, we must also read concurrently, so we’ll require two goroutines calling our multiplex
function. As usual with channels, we’ll have to close the multiplexed channel once we are done reading. Finally, we need to synchronize all of this. For that purpose, we’ll employ a WaitGroup
from the sync
package. Putting it all together yields the following:
|
|
Now that we are armed with all the necessary pieces, we can put this together in our main
function:
|
|
When I run this, I get the following output:
|
|
Note that there is no specific ordering of the output, i.e., we are not processing one input from each stream at a time. Moreover, you might get a different output depending on which computer you run this in. As is, this pattern does not care about the ordering of the data in the multiplexed stream.