gpt4 book ai didi

go - 使用具有外部功能的 sync.WaitGroup 的最佳方式

转载 作者:IT王子 更新时间:2023-10-29 01:10:19 26 4
gpt4 key购买 nike

我对以下代码有一些问题:

package main

import (
"fmt"
"sync"
)
// This program should go to 11, but sometimes it only prints 1 to 10.
func main() {
ch := make(chan int)
var wg sync.WaitGroup
wg.Add(2)
go Print(ch, wg) //
go func(){

for i := 1; i <= 11; i++ {
ch <- i
}

close(ch)
defer wg.Done()


}()

wg.Wait() //deadlock here
}

// Print prints all numbers sent on the channel.
// The function returns when the channel is closed.
func Print(ch <-chan int, wg sync.WaitGroup) {
for n := range ch { // reads from channel until it's closed
fmt.Println(n)
}
defer wg.Done()
}

我在指定的地方遇到了死锁。我尝试设置 wg.Add(1) 而不是 2,它解决了我的问题。我认为我没有成功地将 channel 作为参数发送给 Printer 函数。有没有办法做到这一点?否则,我的问题的解决方案是将 go Print(ch, wg) 行替换为:

go func() {
Print(ch)
defer wg.Done()
}

并将 Printer 函数更改为:

func Print(ch <-chan int) {
for n := range ch { // reads from channel until it's closed
fmt.Println(n)
}

}

什么是最好的解决方案?

最佳答案

好吧,首先你的实际错误是你给 Print 方法一个 sync.WaitGroup 的副本,所以它不调用 Done() 方法在你正在 Wait() 上。

试试这个:

package main

import (
"fmt"
"sync"
)

func main() {
ch := make(chan int)

var wg sync.WaitGroup
wg.Add(2)

go Print(ch, &wg)

go func() {
for i := 1; i <= 11; i++ {
ch <- i
}
close(ch)
defer wg.Done()
}()

wg.Wait() //deadlock here
}

func Print(ch <-chan int, wg *sync.WaitGroup) {
for n := range ch { // reads from channel until it's closed
fmt.Println(n)
}
defer wg.Done()
}

现在,更改您的 Print 方法以删除它的 WaitGroup 通常是个好主意:该方法不需要知道有什么正在等待它完成它的工作。

关于go - 使用具有外部功能的 sync.WaitGroup 的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36407206/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com