worker

package
v0.11.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 5, 2023 License: Apache-2.0 Imports: 6 Imported by: 0

Documentation

Overview

Package worker defines abstractions for parallelizing tasks.

Index

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.

Types

type Result

type Result[T any] struct {
	Value T
	Error error
}

Result is the final result returned to the caller.

type Void

type Void struct{}

Void is a convenience struct for workers that do not actually return values.

type WorkFunc

type WorkFunc[T any] func() (T, error)

WorkFunc is a function for executing work.

type Worker

type Worker[T any] struct {
	// contains filtered or unexported fields
}

Worker represents an instance of a worker. It is same for concurrent use, but see function documentation for more specific semantics.

func New

func New[T any](concurrency int64) *Worker[T]

New creates a new worker that executes work in parallel, up to the maximum provided concurrency. Work is guaranteed to be executed in the order in which it was enqueued, but is not guaranteed to complete in the order in which it was enqueued (i.e. this is not a pipeline).

If the provided concurrency is less than 1, it defaults to the number of CPU cores.

func (*Worker[T]) Do

func (w *Worker[T]) Do(ctx context.Context, fn WorkFunc[T]) error

Do adds new work into the queue. If there are no available workers, it blocks until a worker becomes available or until the provided context is cancelled. The function returns when the work has been successfully scheduled.

To wait for all work to be completed and read the results, call worker.Done. This function only returns an error on two conditions:

Never call Do from within a Do function because it will deadlock.

func (*Worker[T]) Done

func (w *Worker[T]) Done(ctx context.Context) ([]*Result[T], error)

Done immediately stops the worker and prevents new work from being enqueued. Then it waits for all existing work to finish and results the results.

The results are returned in the order in which jobs were enqueued into the worker. Each result will include a result value or corresponding error type. The function itself returns an error only if the context is cancelled.

If the worker is already done, it returns ErrStopped.

func (*Worker[T]) Wait

func (w *Worker[T]) Wait(ctx context.Context) error

Wait blocks until all queued jobs are finished.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL