Today we will take a deep dive into channels and its workings.
We all love to put
go before functions to make them concurrent, but do we know how to control, share data in between go-routines? Today we will take a deep dive into channels and it’s working.
There are two types of channels:
Buffered channel and
A Buffered channel has the capacity to hold one or more values before they are received so they are used to perform asynchronous communication.a
Un-buffered channels don’t have any capacity that’s why they are used to perform synchronous communication between go-routines. It guarantees that the exchange between two go-routine is performed at the instant the send and receive take place. When we create a channel, channels have these properties within.
Let’s create a channel first, that’s simple.
Here’s how we pass data to a go-routine through the channel. What will be the output?
output: 10 is the data from channel
How? We are passing data in the function in the line next to the
go func_name(c) then how this go-routine is getting data from the
c <- 10
To understand this we have to dig deeper into the internal working of channels.
Let’s break the whole code execution into steps and see what's going on more clearly.
1: We declared a function
func_name() which will print the data of the channel
c chan int
2: We declare the main function
3: We now created a channel
c:= make(chan int)
4: Now we passed the channel to the
func_name(c) go-routine. but go-routine is blocked as of now, due to no data in the channel.
5: What happened is, we have two go-routines now.
6: We are putting data to channel
c <- 10 , this blocked our
main go-routine and waiting for
func_name to read the data. Now we have pushed data to our channel, the go scheduler now schedules
func_name go-routine and it will read and print the value, now the execution of
func_name is over.
7: Now the main go-routine unblocks and completes execution.
Hope you now have a clear idea of how channels work.
That’s all for this one. I will be writing some more about channels in my next article.
Thank you for reading.