Go关闭通道实例

关闭通道表示不会再发送更多值。这对于将完成通信到通道的接收器是很有用的。

在这个例子中,我们将使用一个作业通道来完成从main()goroutine到worker goroutine的工作。当没有更多的工作时,则将关闭工作通道。

这里是工作程序goroutine。 它反复从j的工作接收more := <-jobs。在这种特殊的2值形式的接收中,如果作业已关闭并且已经接收到通道中的所有值,则 more 的值将为 false。当已经完成了所有的工作时,使用这个通知。

这会通过作业通道向工作线程发送3个作业,然后关闭它。

等待工作程序,可使用前面看到的同步方法。

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.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通道范围实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程