Go by Example: Closing Channels

Closing a channel indicates that no more values will be sent on the channel. This can be useful to communicate completion to the channel’s receivers.

A sender can close a channel by using the close built-in function. Closing a channel is not the same as sending the zero value on the channel. When a channel is closed, any pending send operations will panic, but receive operations will continue to succeed until all values have been received.

Here’s an example of closing a channel and receiving all values from the channel in a for loop:

package main

import "fmt"

func main() {
    jobs := make(chan int, 5)
    done := make(chan bool)

    go func() {
        for {
            j, more := <-jobs
            if more {
                fmt.Println("received job", j)
            } else {
                fmt.Println("received all jobs")
                done <- true
                return
            }
        }
    }()

    for j := 1; j <= 3; j++ {
        jobs <- j
        fmt.Println("sent job", j)
    }
    close(jobs)
    fmt.Println("sent all jobs")

    <-done
}

The program outputs:

sent job 1
received job 1
sent job 2
received job 2
sent job 3
received job 3
sent all jobs
received all jobs

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *