Created
November 11, 2021 22:51
-
-
Save justinschuldt/24c5a9be2218e66cfcf528c45d4cb6b4 to your computer and use it in GitHub Desktop.
golang parallel async tasks, results via channel
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" | |
) | |
type QueryResult struct { | |
key string | |
result string | |
} | |
func main() { | |
// runs taks in parallel, | |
// publishes results to a channel, | |
// loops to pull data from the channel, to collect results. | |
start := time.Now() | |
queries := map[string]string{ | |
"a": "...", | |
"b": "...", | |
"c": "...", | |
} | |
numQueries := len(queries) | |
resultChan := make(chan QueryResult) | |
for key, query := range queries { | |
go func(k, q string) { | |
fmt.Printf("Going to query for key %s...\n", k) | |
// sleep to mock a long running task | |
time.Sleep(time.Duration(2) * time.Second) | |
res := QueryResult{ key: k, result: "result" } | |
resultChan <- res | |
}(key, query) | |
} | |
results := map[string]string{} | |
for i := 0; i < numQueries; i++ { | |
res := <-resultChan | |
results[res.key] = res.result | |
} | |
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