gpt4 book ai didi

loops - 将 goroutine 的结果传递给循环内的变量

转载 作者:数据小太阳 更新时间:2023-10-29 03:13:04 27 4
gpt4 key购买 nike

在下面的代码中,如何将 slowExternalFunction 的结果分配给适当的 person?它可以通过 channel 完成,为了清楚起见,我定义了 slowExternalFunction 返回 int

type Person struct {
Id int
Name string
WillDieAt int
}

func slowExternalAPI(i int) int {
time.Sleep(10)
willDieAt := i + 2040
return willDieAt
}

func fastInternalFunction(i int) string {
time.Sleep(1)
return fmt.Sprintf("Ivan %v", i)
}

func main() {
var persons []Person

for i := 0; i <= 100; i++ {
var person Person
person.Id = i
person.Name = fastInternalFunction(i)
go slowExternalAPI(i)
person.WillDieAt = 2050 //should be willDieAt from the slowExternalAPI
persons = append(persons, person)
}
fmt.Printf("%v", persons)
}

https://play.golang.org/p/BRBgtH5ryo

最佳答案

要使用 channel 来做到这一点,您必须大量重构您的代码。

最小的改变是在 goroutine 中进行赋值:

go func(){
person.WillDieAt = slowExternalFunction(i)
}()

但是,为了使这项工作正常进行,我们还需要进行一些其他更改:

  • 使用指针数组,以便您可以在分配完成之前添加人员。
  • 实现 WaitGroup ,以便在打印结果之前等待所有 goroutine 完成。

下面是完整的 main 函数,其中进行了更改:

func main() {
var persons []*Person
var wg sync.WaitGroup

for i := 0; i <= 100; i++{
person := &Person{}
person.Id = i
person.Name = fastInternalFunction(i)
wg.Add(1)
go func(){
person.WillDieAt = slowExternalFunction(i)
wg.Done()
}()

persons = append(persons,person)
}
wg.Wait()
for _, person := range persons {
fmt.Printf("%v ", person )
}
}

Playground :https://play.golang.org/p/8GWYD29inC

关于loops - 将 goroutine 的结果传递给循环内的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45685024/

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