Skip to content
Permalink
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
67 lines (49 sloc) 1.83 KB
/*
Title: 30.Closing_Channels.go
Author: OpenSource
Date: 2017-05-21
Description: For Study
Closing a channel indicates that no more values will be sent on it.
This can be useful to communicate completion to the channel’s receivers.
*/
package main
import "fmt"
func main() {
fmt.Println("30.Closing_Channels.go---------Start------------\n\n")
// In this example, we’ll use a jobs channel to communicate work to be done
// from the main() goroutine to a worker goroutine.
// When we have no more jobs for the worker we’ll close the jobs channel.
jobs := make(chan int, 5)
done := make(chan bool)
fmt.Println("jobs := make(chan int, 5)", jobs)
fmt.Println("done := make(chan bool)", done)
// Here’s the worker goroutine.
// It repeatedly receives from jobs with j, more := <-jobs.
// In this special 2-value form of receive,
// the more value will be false if jobs has been closed and all values
// in the channel have already been received.
// We use this to notify on done when we’ve worked all our jobs.
go func() {
for {
j, more := <- jobs
if more{
fmt.Println("received job", j)
} else {
fmt.Println("received all jobs")
done <- true
return
}
}
}()
// This sends 3 jobs to the worker over the jobs channel, then closes it.
for j := 1; j <= 3; j++{
jobs <- j
fmt.Println("sent job", j)
}
close(jobs)
fmt.Println("send all jobs")
// We await the worker using the synchronization(exam 25.Channel Sync.) approach we saw earlier.
// The idea of closed channels leads naturally to our next example: range over channel.
<- done
fmt.Println("\n\n30.Closing_Channels.go----------End-------------")
}
You can’t perform that action at this time.