Created
May 23, 2021 15:21
-
-
Save luqmansen/a8e644733f051e7712e563315621449b to your computer and use it in GitHub Desktop.
Golang Make sure all goroutine function executed unless there is an error
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" | |
"fmt" | |
"log" | |
"os" | |
"strconv" | |
"sync" | |
"time" | |
) | |
func main() { | |
errChan := make(chan error) | |
wg := sync.WaitGroup{} | |
wg.Add(2) | |
go func() { | |
defer wg.Done() | |
err := process(1) | |
if err != nil { | |
log.Println("Error 1") | |
errChan <- err | |
} | |
}() | |
go func() { | |
defer wg.Done() | |
err := process(2) | |
if err != nil { | |
log.Println("Error 2") | |
errChan <- err | |
} | |
}() | |
go func() { | |
select { | |
case err := <-errChan: | |
fmt.Println(err) | |
os.Exit(1) | |
} | |
}() | |
wg.Wait() | |
} | |
func process(procX int) error { | |
time.Sleep(time.Duration(procX) * time.Second) | |
if procX == 2{ | |
return errors.New("error happen") | |
} | |
fmt.Println("PROCESS " + strconv.Itoa(procX) + " DONE") | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The use case would be: when you want to make sure all process are executed concurrently but want to discard the whole thing if there is an error in one of the process