Golang - What is the size of the channel buffer?

I am trying to create an asynchronous channel and I was watching 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 exactly does buffer size / size mean?

+54
go channel
Aug 13 2018-12-12T00:
source share
2 answers

Buffer size is the number of elements that can be sent to the channel without blocking the send. By default, the channel has a buffer size of 0 (you get this with make(chan int) ). This means that each parcel will be blocked until another channel receives from the channel. A buffer size channel 1 may contain 1 element before sending blocks, so you will get

 c := make(chan int, 1) c <- 1 // doesn't block c <- 2 // blocks until another goroutine receives from the channel 
+106
Aug 13 2018-12-12T00:
source share

The following code illustrates blocking an 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 can play with the code here .

+2
07 Oct '16 at 14:18
source share



All Articles