Skip to content

Instantly share code, notes, and snippets.

@matryer
Last active August 17, 2020 02:58
Show Gist options
  • Save matryer/20e2ea821f9df470377084eda6ef0dcb to your computer and use it in GitHub Desktop.
Save matryer/20e2ea821f9df470377084eda6ef0dcb to your computer and use it in GitHub Desktop.
Async helper function for Go.
// Released under MIT License
package main
import "sync"
// asyncFn is a function that can be run asychronously by
// async.
type asyncFn func() error
// async runs many functions at the same time.
// Returns the last not-nil error.
func async(fns ...asyncFn) error {
var errLock sync.Mutex // protects errResult
var errResult error
var wg sync.WaitGroup
wg.Add(len(fns))
for i := range fns {
go func(i int) {
defer wg.Done()
if err := fns[i](); err != nil {
errLock.Lock()
errResult = err
errLock.Unlock()
}
}(i)
}
wg.Wait()
if errResult != nil {
return errResult
}
return nil
}
Copy link

ghost commented Aug 14, 2020

👍

Here is my approach to the same need, but inspired from Java executors somehow. In some scenarios it becomes useful, Specially when you are going to handle a lot of concurrent functions that need to work with same data (High contention rate) or when you are doing batch jobs and don’t want to bother the go runtime.

@earthboundkid
Copy link

I have an errutil.ExecParallel function that is similar, but it relies on errutil.Slice, which can turn a []error into a Multierror. This way you capture all the errors, not just the first.

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