-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchannel_close.go
More file actions
36 lines (36 loc) · 1.31 KB
/
channel_close.go
File metadata and controls
36 lines (36 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
package main
import "fmt"
import "runtime"
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
//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.
func main() {
jobs := make(chan int)
done := make(chan bool)
//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.
go func() {
for j := 1; j <= 100; j++ {
fmt.Println("sent job", j)
jobs <- j
//runtime.Gosched()
}
close(jobs)
fmt.Println("sent all jobs")
}()
//We await the worker using the synchronization approach we saw earlier.
<-done
}