2017-08-15 4 views
0

slowExternalFunctionから適切なに結果を割り当てるには、下のコードで?チャンネルを介して行うことができ、わかりやすくするために、slowExternalFunctionを返します。goroutineの結果をループ内の変数に渡す

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

答えて

0

あなたのコードはかなりをリファクタリングする必要があるでしょうチャネルを使用して、それを行うには。

変更はゴルーチンでの割り当てを行うことであろう最小:我々は同様に他のいくつかの変更を行う必要があると思い、この作品を作るために、しかし

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

を:

  • 配列を使用します割り当ての完了前に人を追加することができるようにします。
  • 結果を出力する前にすべてのゴルーチンが終了するのを待つように、待機グループを実装します。

    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

は、ここで変更で完全main機能です

関連する問題