Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is channel buffer size?

Tags:

go

channel

I'm trying to create an asynchronous channel and I've been looking at http://golang.org/ref/spec#Making_slices_maps_and_channels.

c := make(chan int, 10)         // channel with a buffer size of 10 

What does it mean that the buffer size is 10? What specifically does the buffer size represent/limit?

like image 400
Tech163 Avatar asked Aug 13 '12 23:08

Tech163


People also ask

What is channel buffer?

Buffered channels allows to accept a limited number of values without a corresponding receiver for those values. It is possible to create a channel with a buffe. Buffered channel are blocked only when the buffer is full. Similarly receiving from a buffered channel are blocked only when the buffer will be empty.

What's the default buffer size of the channel in go?

By default, a channel buffer size is 0 also called as unbuffered channel.

What is channel size in Golang?

First off, the maximum message size (or channel type) is 2^16 bytes, or 64 kilobytes.

What happens when a buffered channel is full?

Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty. Modify the example to overfill the buffer and see what happens.


2 Answers

The buffer size is the number of elements that can be sent to the channel without the send blocking. By default, a channel has a buffer size of 0 (you get this with make(chan int)). This means that every single send will block until another goroutine receives from the channel. A channel of buffer size 1 can hold 1 element until sending blocks, so you'd get

c := make(chan int, 1) c <- 1 // doesn't block c <- 2 // blocks until another goroutine receives from the channel 
like image 62
Lily Ballard Avatar answered Oct 20 '22 01:10

Lily Ballard


The following code illustrates the blocking of unbuffered channel:

// to see the diff, change 0 to 1 c := make(chan struct{}, 0) go func() {     time.Sleep(2 * time.Second)     <-c }() start := time.Now() c <- struct{}{} // block, if channel size is 0 elapsed := time.Since(start) fmt.Printf("Elapsed: %v\n", elapsed) 

You may play with the code here.

like image 28
Vladimir Bauer Avatar answered Oct 20 '22 02:10

Vladimir Bauer