Skip to content

Instantly share code, notes, and snippets.

@hosszukalman
Created April 16, 2020 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hosszukalman/fc0f8a341ae99c50dbaaacdde86e8acd to your computer and use it in GitHub Desktop.
Save hosszukalman/fc0f8a341ae99c50dbaaacdde86e8acd to your computer and use it in GitHub Desktop.
An example how to use waitgroup in go.
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