Back to: Golang
Go language provides a feature called channels for communication between goroutines. A channel can be thought of as a pipe that connects the goroutines to each other for the transfer of data. This enables the goroutines to synchronize and communicate with each other efficiently.
A channel is created using the make
function, and the direction of the channel can be specified as send-only (chan<-
) or receive-only (<-chan
) or bi-directional (chan
). The channel can be of any type.
Here is an example of creating an integer channel:
ch := make(chan int)
The ch
variable is now a channel that can be used to send and receive integers between goroutines.
To send a value on a channel, the <-
operator is used:
ch <- 10
This sends the integer value 10 on the ch
channel.
To receive a value from a channel, the <-
operator is used:
x := <-ch
This receives the integer value sent on the ch
channel and stores it in the variable x
.
Channels can be used for synchronization between goroutines. For example, consider the following code snippet:
package main
import (
"fmt"
"time"
)
func worker(ch chan bool) {
fmt.Println("Worker started")
time.Sleep(time.Second * 2)
fmt.Println("Worker finished")
ch <- true
}
func main() {
ch := make(chan bool)
go worker(ch)
fmt.Println("Waiting for worker to finish")
<-ch
fmt.Println("Worker has finished")
}
In this code, the worker
function is called as a goroutine, and a channel ch
is passed as an argument. The main
function waits for the worker to finish by receiving a value on the channel. When the worker finishes, it sends a boolean value on the channel, which is received by the main function, indicating that the worker has finished.
Channels can also be used for buffering data. A buffered channel can hold a limited number of values before it blocks the sending goroutine. The capacity of a channel can be specified during its creation using the second argument of the make
function.
ch := make(chan int, 3)
This creates a buffered channel with a capacity of 3 integers.
Here’s an example of a buffered channel:
package main
import (
"fmt"
)
func main() {
ch := make(chan int, 3)
ch <- 1
ch <- 2
ch <- 3
fmt.Println(<-ch)
fmt.Println(<-ch)
fmt.Println(<-ch)
}
In this example, we create a buffered channel ch
with a capacity of 3. We then send 3 integers on the channel, and then receive and print them in the same order as they were sent.
Follow us on social media
Follow Author