Skip to content

Instantly share code, notes, and snippets.

@luqmansen
Created May 23, 2021 15:21
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 luqmansen/a8e644733f051e7712e563315621449b to your computer and use it in GitHub Desktop.
Save luqmansen/a8e644733f051e7712e563315621449b to your computer and use it in GitHub Desktop.
Golang Make sure all goroutine function executed unless there is an error
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
}
@luqmansen
Copy link
Author

luqmansen commented May 23, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment