Closing Channels
package main
import "fmt"
func main() {
// Creating a buffered channel 'jobs' with a capacity of 5
jobs := make(chan int, 5)
// Creating an unbuffered channel 'done' for signaling when all jobs are received
done := make(chan bool)
// Launching a goroutine to receive jobs from the 'jobs' channel
go func() {
for {
// Attempting to receive a job from 'jobs'
j, more := <-jobs
if more {
fmt.Println("received job", j)
} else {
// If 'more' is false, it means the 'jobs' channel is closed
fmt.Println("received all jobs")
// Signaling that all jobs are received by sending true to 'done'
done <- true
return
}
}
}()
// Sending three jobs to the 'jobs' channel
for j := 1; j <= 3; j++ {
jobs <- j
fmt.Println("sent job", j)
}
// Closing the 'jobs' channel to indicate that no more jobs will be sent
close(jobs)
fmt.Println("sent all jobs")
// Waiting for the 'done' channel to receive a signal indicating all jobs are received
<-done
// Attempting to receive from the closed 'jobs' channel
_, ok := <-jobs
fmt.Println("received more jobs:", ok)
}Output
Last updated