Created
November 11, 2021 22:53
-
-
Save justinschuldt/d1b4812156ff1463bd7de091ef9c435e to your computer and use it in GitHub Desktop.
golang parallel async tasks, using WaitGroups and Mutex locks
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" | |
"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