Documentation
¶
Overview ¶
Package sync provides concurrency helpers.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Parallel ¶
Parallel runs `fn(0)` through `fn(n-1)` concurrently with at most `workers` in flight, blocking until all complete. Each call receives a distinct index, so a goroutine writing `results[i]` needs no lock; `fn` must otherwise be safe to call concurrently. `workers` < 1 runs one call at a time.
Example ¶
package main
import (
"fmt"
xsync "github.com/gechr/x/sync"
)
func main() {
// Each call receives a distinct index, so writing results[i]
// needs no lock.
results := make([]int, 5)
xsync.Parallel(3, len(results), func(i int) {
results[i] = i * i
})
fmt.Println(results)
}
Output: [0 1 4 9 16]
Example (SingleWorker) ¶
A single worker runs the calls one at a time, in index order.
package main
import (
"fmt"
xsync "github.com/gechr/x/sync"
)
func main() {
xsync.Parallel(1, 3, func(i int) {
fmt.Println("call", i)
})
}
Output: call 0 call 1 call 2
func ParallelErr ¶ added in v0.3.11
ParallelErr is Parallel for tasks that can fail. All `n` calls run regardless of failures - one task's error does not cancel the others. It returns nil if every call succeeded, otherwise an error joining each failure wrapped with its task index; errors.Is and errors.As reach every cause through the join.
Example ¶
package main
import (
"fmt"
xsync "github.com/gechr/x/sync"
)
func main() {
items := []int{2, 7, 4, 9}
err := xsync.ParallelErr(2, len(items), func(i int) error {
if items[i]%2 != 0 {
return fmt.Errorf("odd value %d", items[i])
}
return nil
})
fmt.Println(err)
}
Output: task 1: odd value 7 task 3: odd value 9
Types ¶
This section is empty.