Turn off buffered channel instance analysis in Go language

  • 2020-05-26 09:16:41
  • OfStack

This article analyzes the example of turning off a buffered channel in the Go language. Share with you for your reference. The specific analysis is as follows:

The Go language provides two channels, with and without buffers. For channels without buffers, sending and receiving are synchronous, and the receiving end must receive the message before the sending end can be freed from the sending call. Channels with buffers, sending and receiving are asynchronous until the buffer is full, and the sending operation at the sender is only guaranteed to put the message into the buffer.

The channel of Go can be closed. The purpose of closing the channel is to let the receiver know that no more messages will enter from this channel. We may use the closing of a channel to indicate the end of a certain state.

When we close a channel with a buffer, if there are still messages in the buffer, will the receiver continue to receive the rest of the messages? Or just discard the rest of the message? Here is a test code I did:

package main
import "fmt"
func main() {
    input := make(chan int, 10)
    wait  := make(chan int)
    for i := 0; i < 10; i ++ {
        input <- i
    }
    close(input)
    go func() {
        for {
            if i, ok := <- input; ok {
                fmt.Println(i)
            } else {
                break
            }
        }
        wait <- 1
    }()
    <-wait
}

I hope this article has been helpful to your programming of Go language.


Related articles: