如何处理关闭同一频道的多个 go-routines?

How to handle multiple go-routines closing the same channel?

我有 2 个从单个通道读取的 go-routines。 4 秒后,我取消上下文并终止 select 循环。在终止循环之前,我在通道上调用 close,因为有 2 个 go-routines close 被调用两次并导致恐慌,因为其中一个 go-routines 已经关闭了通道。目前我正在使用 recover 从恐慌中恢复,有更好的方法吗?

package main

import (
    "context"
    "fmt"
    "sync"
    "time"
)

func numberGen(ctx context.Context, numChan chan int) {
    num := 0
    doneCh := ctx.Done()
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered from ", r)
        }
    }()
    for {
        select {
        case <-doneCh:
            fmt.Println("done generating...")
            close(numChan)
            return
        default:
            num++
            numChan <- num
        }
    }
}

func main() {
    ctx, cancelFn := context.WithCancel(context.Background())
    numChan := make(chan int)
    var wg sync.WaitGroup
    wg.Add(2)
    go numberGen(ctx, numChan)
    go numberGen(ctx, numChan)

    go func(cfn context.CancelFunc) {
        time.Sleep(10 * time.Millisecond)
        cfn()
    }(cancelFn)

    for n := range numChan {
        fmt.Println("received value ", n)
    }

    time.Sleep(2 * time.Second)
}

在 goroutines 完成发送值后关闭通道。

var wg sync.WaitGroup
wg.Add(2)
go numberGen(ctx, numChan, &wg)
go numberGen(ctx, numChan, &wg)

go func() {
    wg.Wait()
    close(numChan)
}()

更新 numberGen 以在等待组中调用 Done()。此外,删除对 close.

的调用
func numberGen(ctx context.Context, numChan chan int, wg *sync.WaitGroup) {
    defer wg.Done()
    ...