https://github.com/hackergrrl/parallel
(Go) :fast_forward: Run many functions in parallel, but fast-bail on errors.
https://github.com/hackergrrl/parallel
Last synced: 10 months ago
JSON representation
(Go) :fast_forward: Run many functions in parallel, but fast-bail on errors.
- Host: GitHub
- URL: https://github.com/hackergrrl/parallel
- Owner: hackergrrl
- Created: 2016-02-11T06:52:40.000Z (over 10 years ago)
- Default Branch: master
- Last Pushed: 2017-01-28T03:21:22.000Z (over 9 years ago)
- Last Synced: 2025-04-12T06:13:13.580Z (about 1 year ago)
- Language: Go
- Homepage:
- Size: 3.91 KB
- Stars: 4
- Watchers: 2
- Forks: 3
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# parallel
> Execute many functions in parallel. Immediately return if one returns an
> error.
## Background
A common Go pattern is to execute several independent tasks in parallel and wait
for them to all complete before proceeding. However, the tasks tend to be
all-or-nothing, and you'll want the whole thing to bail if any of them return an
error.
## Examples
Say you have a few long-ish running functions that return errors:
```go
import (
"errors"
"fmt"
parallel "github.com/noffle/parallel"
)
func main() {
err := parallel.Parallel(nil, sleep, sleep)
fmt.Println(err)
}
func sleep() error {
fmt.Printf("sleeping..\n")
time.Sleep(100 * time.Millisecond)
fmt.Printf("..slept!\n")
return errors.New("awoke")
}
```
```
sleeping..
sleeping..
..slept!
..slept!
awoke
```
You can also provide a `chan struct{}` as the first parameter to cancel the
parallel operation early:
```go
func main() {
var bail = make(chan struct{})
parallel.Parallel(bail,
sleep,
func() error {
fmt.Printf("going to bail..\n")
time.Sleep(50 * time.Millisecond)
close(bail)
fmt.Printf("..bailed!\n")
},
)
}
```
outputs
```
sleeping..
going to bail..
..bailed!
```
`parallel` is also compatible with `golang.org/x/net/context`!
```go
func main() {
ctx, bail := context.WithCancel(context.Background())
parallel.Parallel(ctx.Done(),
sleep,
func() error {
time.Sleep(50 * time.Millisecond)
bail()
},
)
}
```
## API
```go
import "github.com/noffle/parallel"
```
### func Parallel(chan struct{}, ...func() error) error
Accepts an optional channel to signal cancellation of the parallel tasks, and a
variable number of functions matching the signature `func() error`.
The first function to return a non-nil error closes the cancel channel (if
non-nil) and propogates its error as the return value.
In the case that the cancel channel is closed, `Parallel` will return
`parallel.Canceled`.
## Install
```
go get github.com/noffle/parallel
```
## License
MIT