Created
April 16, 2020 15:01
-
-
Save hosszukalman/fc0f8a341ae99c50dbaaacdde86e8acd to your computer and use it in GitHub Desktop.
An example how to use waitgroup in go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
) | |
type Foo struct { | |
ID int | |
} | |
type Result struct { | |
Foo | |
Message string | |
} | |
func main() { | |
fmt.Println("Hello, playground") | |
var wg sync.WaitGroup | |
foos := []Foo{ | |
Foo{0}, | |
Foo{1}, | |
Foo{2}, | |
Foo{3}, | |
Foo{4}, | |
Foo{5}, | |
} | |
results := make([]Result, len(foos)) | |
for i := range foos { | |
wg.Add(1) | |
go func(foo Foo, wg *sync.WaitGroup, results []Result) { | |
fmt.Printf("ID: %v started\n", foo.ID) | |
results[foo.ID].Foo = foo | |
results[foo.ID].Message = fmt.Sprintf("The result is created for ID: %v", foo.ID) | |
wg.Done() | |
}(foos[i], &wg, results) | |
} | |
wg.Wait() | |
fmt.Printf("Done, results: %+v", results) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment