Home > other >  Issue sharing array between goroutines
Issue sharing array between goroutines

Time:05-09

I am trying to solve this golang exercise https://github.com/loong/go-concurrency-exercises/tree/master/1-producer-consumer.

I guess I am close to the solution but I am getting a deadlock error

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!

here is my code

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))
}

Where y solution is failing?

Thanks in advance

CodePudding user response:

Deadlock happened because you pass 3 to wg.Add(3), which means creating 3 waiting groups but you only need 1.

Solution is replacing wg.Add(3) with wg.Add(1).

Check my demo code here

  • Related