Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go关闭通道实例
Go关闭通道实例
作者:--    发布时间:2019-11-20

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

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

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

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

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

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册