在 goroutine 之间发布共享数组

Issue sharing array between goroutines

我正在尝试解决这个 golang 练习 https://github.com/loong/go-concurrency-exercises/tree/master/1-producer-consumer

我想我已经接近解决方案了,但我遇到了死锁错误

davecheney      tweets about golang
beertocode      does not tweet about golang
ironzeb         tweets about golang
beertocode      tweets about golang
vampirewalk666  tweets about golang
fatal error: all goroutines are asleep - deadlock!

这是我的代码

func producer(stream Stream) (tweets []*Tweet) {
    for {
        tweet, err := stream.Next()
        if err == ErrEOF {
            return tweets
        }

        tweets = append(tweets, tweet)
    }
}

func consumer(tweets []*Tweet) {
    for _, t := range tweets {
            if t.IsTalkingAboutGo() {
            fmt.Println(t.Username, "\ttweets about golang")
        } else {
            fmt.Println(t.Username, "\tdoes not tweet about golang")
        }
    }
}

func main() {
    start := time.Now()
    stream := GetMockStream()

    data := make(chan []*Tweet)
    var wg sync.WaitGroup

    wg.Add(3)
    // Producer
    go func() {
        tweets := producer(stream)
        data <- tweets
    }()



    // Consumer
    go func() {
        defer wg.Done()
        tweets := <-data
        consumer(tweets)
    }()

    wg.Wait()
    fmt.Printf("Process took %s\n", time.Since(start))
}

你的解决方案在哪里失败了?

提前致谢

发生死锁是因为你把3传递给wg.Add(3),这意味着创建了3个等待组,但你只需要1个。

解决方案是将 wg.Add(3) 替换为 wg.Add(1)

检查我的演示代码here