What are channels
Channels can be thought of as pipes using which Goroutines communicate. Similar to how water flows from one end to another in a pipe, data can be sent from one end and received from the other end using channels.
Declaring channels
Each channel has a type associated with it. This type is the type of data that the channel is allowed to transport. No other type is allowed to be transported using the channel.
var Channel_name chan Type
or
channel_name:= make(chan Type)
The zero value of a channel is nil
. nil
channels are not of any use and hence the channel has to be defined using make
similar to maps and slices.
Example
package main
import (
"fmt"
"time"
)
func hello(done chan bool) {
fmt.Println("hello go routine is going to sleep")
time.Sleep(4 * time.Second)
fmt.Println("hello go routine awake and going to write to done")
done <- true
}
func main() {
done := make(chan bool)
fmt.Println("Main going to call hello go goroutine")
go hello(done)
<-done
fmt.Println("Main received data")
}
In the above program, we have introduced a sleep of 4 seconds to the hello
function in line no. 10.
This program will first print Main going to call hello go goroutine
. Then the hello Goroutine will be started and it will print hello go routine is going to sleep
. After this is printed, the hello
Goroutine will sleep for 4 seconds and during this time main
Goroutine will be blocked since it is waiting for data from the done channel in line no. 18 <-done
. After 4 seconds hello go routine awake and going to write to done
will be printed followed by Main received data
.
If you found this helpful, make sure to show your support with a clap, and if you want to help others in their projects, a share would be greatly appreciated! Let me know what you think about this! Happy Learning Go!