【问题标题】:Pass a result from goroutine to a variable inside the loop将 goroutine 的结果传递给循环内的变量
【发布时间】:2018-01-22 21:53:50
【问题描述】:

在下面的代码中,如何将 slowExternalFunction 的结果分配给适当的 person?它可以通过渠道来完成,为了清楚起见,我定义了 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

【问题讨论】:

    标签: loops go goroutine


    【解决方案1】:

    要使用通道,您必须对代码进行相当多的重构。

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

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

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

    • 使用指针数组,以便您可以在分配完成之前添加人员。
    • 实现一个等待组,以便在打印结果之前等待所有 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 )
        }
    }
    

    游乐场:https://play.golang.org/p/8GWYD29inC

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      相关资源
      最近更新 更多