问题:在Go协程之间共享数组的问题。

huangapple go评论77阅读模式
英文:

Issue sharing array between goroutines

问题

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

我猜我离解决方案很近,但是我遇到了死锁错误。

这是我的代码:

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

我的解决方案哪里出错了?

提前感谢。

英文:

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, &quot;\ttweets about golang&quot;)
		} else {
			fmt.Println(t.Username, &quot;\tdoes not tweet about golang&quot;)
		}
	}
}

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 &lt;- tweets
	}()



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

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

Where y solution is failing?

Thanks in advance

答案1

得分: 0

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

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

你可以在这里查看我的演示代码。

英文:

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

huangapple
  • 本文由 发表于 2022年5月6日 15:56:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/72137996.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定