英文:
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, "\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
答案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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论