Forked from jayjayswal/Wait result of multiple goroutines
Created
October 10, 2021 06:55
-
-
Save virtualsafety/e0236766ce703ea5b5c8d5370bad4412 to your computer and use it in GitHub Desktop.
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 ( | |
"errors" | |
"sync" | |
) | |
func test(i int) (int, error) { | |
if i > 2 { | |
return 0, errors.New("test error") | |
} | |
return i + 5, nil | |
} | |
func test2(i int) (int, error) { | |
if i > 3 { | |
return 0, errors.New("test2 error") | |
} | |
return i + 7, nil | |
} | |
func main() { | |
results := make(chan int, 2) | |
errors := make(chan error, 2) | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
result, err := test(3) | |
if err != nil { | |
errors <- err | |
return | |
} | |
results <- result | |
}() | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
result, err := test2(3) | |
if err != nil { | |
errors <- err | |
return | |
} | |
results <- result | |
}() | |
// here we wait in other goroutine to all jobs done and close the channels | |
go func() { | |
wg.Wait() | |
close(results) | |
close(errors) | |
}() | |
for err := range errors { | |
// here error happend u could exit your caller function | |
println(err.Error()) | |
return | |
} | |
for res := range results { | |
println("--------- ", res, " ------------") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://stackoverflow.com/questions/62140859/aggregating-results-from-multiple-go-routines-with-common-channel