我有一个goroutine,它调用一个方法,并在一个通道上传递返回值:

ch := make(chan int, 100)
go func(){
    for {
        ch <- do_stuff()
    }
}()

我怎样才能阻止这样的一场闹剧?

推荐答案

EDIT: I wrote this answer up in haste, before realizing that your question is about sending values to a chan inside a goroutine. The approach below can be used either with an additional chan as suggested above, or using the fact that the chan you have already is bi-directional, you can use just the one...

如果您的goroutine仅用于处理来自chan的项目,您可以使用"关闭"内置和频道的特殊接收表单.

也就是说,一旦你发送完chan上的项目,你就可以关闭它.然后在goroutine中,你会得到一个额外的参数给receive操作符,显示通道是否已关闭.

下面是一个完整的示例(等待组用于确保该过程继续,直到goroutine完成):

package main

import "sync"
func main() {
    var wg sync.WaitGroup
    wg.Add(1)

    ch := make(chan int)
    go func() {
        for {
            foo, ok := <- ch
            if !ok {
                println("done")
                wg.Done()
                return
            }
            println(foo)
        }
    }()
    ch <- 1
    ch <- 2
    ch <- 3
    close(ch)

    wg.Wait()
}

Go相关问答推荐

使用Gorm创建自定义连接表

无法在Macos上使用Azure Speech golang SDK

Golang XML密钥名称冲突

从使用Golang otelmux检测的Otel跟踪中获取trace_id

`docker system df` 与 `/system/df` (docker api 端点)

Golang Fiber Render - 将数据发送到多个布局

Golang telegram 机器人

为什么我只收到部分错误而不是我启动的 goroutines 的所有错误?

杜松子wine 和中间件

如何在自定义验证函数中获取 struct 名称

来自洪流公告的奇怪同行字段

在 go 中将运行命令的标准输出发送到其标准输入

无法建立连接,因为目标机器主动拒绝它 Golang

关系不存在 GORM

Golang ACMEv2 HTTP-01 挑战不挑战服务器

Go 赋值涉及到自定义类型的指针

Go:如何通过 GIN-Router 从 AWS S3 将文件作为二进制流发送到浏览器?

comparable和any有什么区别?

在 Go 中表达函数的更好方法( struct 方法)

Golang 中的无实体函数