We can specify a fixed capacity for a channel and create a buffered channel.
If the channel has a buffer, the sender will only block until the value has been pushed into the buffer. If the buffer is full, the sender blocks until a receiver retrieves a value.
Let us look at a worked-out example to further understand this concept.
package mainimport "fmt"func main() {fmt.Printf("Hello World \n")ch := make(chan string, 2)ch <- "hello "ch <- "golang"fmt.Printf(<-ch)fmt.Printf(<-ch)}
In the above example, we see that we can send two values into channel ch
without blocking since the capacity is 2.
However, if we try to overfill the buffer, we will receive a deadlock error. This is shown in the example below.
package mainimport "fmt"func main() {ch := make(chan int, 4)ch <- 1ch <- 2ch <- 3ch <- 4ch <- 5fmt.Println(<-ch)fmt.Println(<-ch)fmt.Println(<-ch)fmt.Println(<-ch)}
One of the main uses of buffered channels is to limit the number of workers queued up. This is particularly useful in network I/O or Disk I/O intensive compute scenarios.
Free Resources