Map / Filter / Pool
The package provides high-level functions to work with collections, such as Map, Filter, and Pool.
Behavior of Map and Filter is similar to their counterparts in slice package. The difference is that they run functions in parallel. Please note, performance is usually lower than using slice package! Use them only if you know that cpu/io cost of a logic is higher than goroutines spin up cost.
go
// Example of Map function.
results := async.Map(slice.Range(1, 1000), func(v int) int {
return Workload(v)
})
// Example of Filter function.
results := async.Filter(slice.Range(1, 1000), func(v int) bool {
return v < 500
})
In addition to Map and Filter, the package provides Pool function. It creates a pool of workers and channels for input and output.
go
// Task holds processing data, like id, input, and result.
type Task struct {
ID int
Value int
Result int
}
// Spin up a pool of 10 workers.
in, out := async.Pool(10, func(v *Task) *Task {
return Workload(v)
})
// Send 1000 tasks to the pool.
go func() {
for i := 0; i < 1000; i++ {
in <- &Task{ID: i, Value: i}
}
close(in)
}()
// Read results from the pool.
// Out channel will be closed automatically on input channel close
// and workers completion.
for v := range out {
fmt.Println(v.ID, v.Result)
}