如何等待 goroutines 完成并在没有锁的情况下读取通道?

How to wait for goroutines to finish and read the channel without a lock?

我在 SO 上查看了许多示例和问题,但仍然无法获得按预期工作的相当简单的代码:

func main() {
    ch := make(chan string)
    var wg sync.WaitGroup
    wg.Add(2)
    go readFile("A", ch, wg)
    go readFile("B", ch, wg)
    go func() {
        wg.Wait()
        close(ch)
    }()
    printer(ch)
}

func readFile(name string, ch chan string, wg sync.WaitGroup) {
    file, err := os.Open(name)
    if err != nil {
        fmt.Errorf("was not able to read from file %s: %s", name, err)
    }
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        ch <- scanner.Text()
    }
    wg.Done()
}

func printer(ch chan string) {
    for val := range ch {
        fmt.Println(val)
    }
}

所以我从两个文件中读取,将读取的行推送到一个通道中,然后简单地将它们打印出来(一些代码从不需要的细节中简化)

两个goroutines,他们两个都是WaitGroup,用Wait修复goroutine并关闭channel。

从我的角度来看,这与这个问题和例外答案几乎相同:Let golang close used channel after all goroutines finished

那么我的情况出了什么问题?

首先按照 sync.WaitGroup 说明的文档操作:

Package sync

import "sync"

type WaitGroup

A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and calls Done when finished. At the same time, Wait can be used to block until all goroutines have finished.

A WaitGroup must not be copied after first use.


A WaitGroup must not be copied after first use.