Documentation
¶
Overview ¶
Package worker defines abstractions for parallelizing tasks.
Example (HTTP) ¶
package main
import (
"context"
"fmt"
"io"
"net/http"
"github.com/abcxyz/pkg/worker"
)
func main() {
ctx := context.TODO()
w := worker.New[string](0)
urls := []string{
"https://apple.com",
"https://example.com",
"https://google.com",
}
for _, u := range urls {
// Make a local copy for the closure.
u := u
if err := w.Do(ctx, func() (string, error) {
resp, err := http.Get(u)
if err != nil {
return "", err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(b), nil
}); err != nil {
// TODO: check err
}
}
results, err := w.Done(ctx)
if err != nil {
// TODO: check err
}
for i, result := range results {
fmt.Printf("%s: body(%d), err(%v)\n", urls[i], len(result.Value), result.Error)
}
}
Output:
Example (Sleep) ¶
package main
import (
"context"
"time"
"github.com/abcxyz/pkg/worker"
)
func main() {
ctx := context.TODO()
w := worker.New[*worker.Void](3)
for i := 0; i < 5; i++ {
if err := w.Do(ctx, func() (*worker.Void, error) {
time.Sleep(10 * time.Millisecond)
return nil, nil
}); err != nil {
// TODO: check err
}
}
results, err := w.Done(ctx)
if err != nil {
// TODO: check err
}
_ = results
}
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
View Source
var ErrStopped = fmt.Errorf("worker is stopped")
ErrStopped is the error returned when the worker is stopped.
Functions ¶
This section is empty.