Buffered Channel in Golang


A buffered channel in Golang is a particular kind of channel that enables several values to be transmitted and received without blocking. In this post, we'll talk about buffered channels in Golang, their syntax, and some real-world uses.

What is a Buffered Channel?

In Golang, a channel type that can keep a predetermined number of values before blocking is known as a buffered channel. As long as there is space in the buffer, this permits sending and receiving numerous values without blocking. Any additional attempts to send data will be blocked after the buffer is filled until more room is available.

Syntax

The syntax for creating a buffered channel in Golang is as follows −

make(chan type, capacity)

Here, "type" is the type of data that will be sent and received through the channel, and "capacity" is the number of values that can be stored in the buffer.

Example

The following code demonstrates how to create and use a buffered channel in Golang −

package main

import "fmt"

func main() {
   ch := make(chan int, 2)
   ch <- 1
   ch <- 2
   fmt.Println(<-ch)
   fmt.Println(<-ch)
}

Output

1
2

In this example, we created a buffered channel of type int with a capacity of 2. We then sent two values into the channel using the "ch <-" syntax. Finally, we received the values from the channel using the "<- ch" syntax. Since the buffer had available space, the values were sent and received without blocking.

Practical Applications

In Golang, buffered channels can be used for a variety of useful purposes, such as −

  • Performance Benefits − By decreasing the amount of time goroutines have to wait for communication, buffered channels can help concurrent programmes run more efficiently.

  • Timeouts − The select statement and buffered channels can be used to implement timeouts in Golang programmes. The software can go on to the following case in the select statement if a value cannot be delivered or received within a predetermined amount of time.

  • Resource Management − Limited resources, such as database connections or file handles, can be managed via buffered channels. Programs can prevent the system from becoming overloaded and crashing by restricting the amount of resources that can be used at once.

Conclusion

In Golang, buffered channels are a powerful tool for controlling communication between running goroutines. As long as the buffer has room, they enable numerous values to be sent and received without blocking. Timeouts, resource management, and concurrent programme performance can all be improved by buffered channels. Buffered channels are a crucial tool for any Golang coder working with concurrent programming because of all the practical uses they have.

Updated on: 06-Apr-2023

419 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements