Skip to content

Instantly share code, notes, and snippets.

@justinschuldt
Created November 11, 2021 22:53
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 justinschuldt/d1b4812156ff1463bd7de091ef9c435e to your computer and use it in GitHub Desktop.
Save justinschuldt/d1b4812156ff1463bd7de091ef9c435e to your computer and use it in GitHub Desktop.
golang parallel async tasks, using WaitGroups and Mutex locks
package main
import (
"fmt"
"time"
"sync"
)
type QueryResult struct {
key string
result string
}
func main() {
// runs taks in parallel,
// mutates the "results" map to collect all the results
start := time.Now()
queries := map[string]string{
"a": "...",
"b": "...",
"c": "...",
}
numQueries := len(queries)
var wg sync.WaitGroup
wg.Add(numQueries)
var mu sync.RWMutex
results := map[string]string{}
for key, query := range queries {
go func(k, q string) {
defer wg.Done()
fmt.Printf("Going to query for key %s...\n", k)
// sleep to mock a long running task
time.Sleep(time.Duration(2) * time.Second)
mu.Lock()
results[k] = "result"
mu.Unlock()
}(key, query)
}
wg.Wait()
fmt.Println("collected results:", results)
fmt.Println("took", time.Since(start))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment