Channels in Go
Creating concurrent programs in Go has a unique approach to handle and to implementation when we want share memory to communication. The approach is to share memory by communicating, instead of communicating by sharing memory which is not allowed in Go. This approach can be done by using channels that can be used by goroutines to communicate with each other.
To create a channel in Go, one can use the make()
function.
Note that when creating a channel there are certain data types that need to be attached. This type can be any type supported by Golang. Attaching values to channels and retrieving values from channels can be done using this syntax.
There are several concurrency patterns that can be used to create concurrent programs in Go. The concurrency patterns that will be discussed in this blog are fan in, and fan out.
Fan In Implementation
*Fan In is a concurrency pattern that takes multiple inputs and uses them in a single channel. The Fan In Pattern works like a multiplexer. Here is a simple visualization of Fan In.
Here is a simple example using channel
program output:
Channel B -> 47
<- 47
Channel B -> 81
<- 81
Channel A -> 25
<- 25
Channel B -> 56
<- 56
Channel B -> 94
<- 94
Channel B -> 62
<- 62
Channel B -> 28
<- 28
Channel B -> 11
<- 11
Channel A -> 37
<- 37
Channel A -> 95
<- 95
Channel B -> 28
<- 28
Based on the code displayed above, the data will be entered into 2 channels, namely channel A and channel B. Furthermore, it is printed with channel C where only channel C will print all input data from various channels.
Fan Out Implementation
Fan Out Pattern is a concurrency patter where many functions can read from the same channel until the channel is closed. Usually fan in and fan out patterns can be used simultaneously. Here is a simple visualization of Fan Out.
directly on the following sample example
Program output:
-> 87
consumer B <- 87
-> 59
consumer B <- 59
-> 18
consumer A <- 18
-> 40
consumer A <- 40
-> 0
consumer A <- 0
Based on the code created above, fan out is used for multiple outputs where if there is data entered in one channel, it will be processed by several channels that have been provided, in this code, the channels that process are channel A and channel B.