Documentation ¶
Overview ¶
Package worker defines abstractions for parallelizing tasks.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrStopped = fmt.Errorf("worker is stopped")
ErrStopped is the error returned when the worker is stopped.
Functions ¶
This section is empty.
Types ¶
type Void ¶
type Void struct{}
Void is a convenience struct for workers that do not actually return values.
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 ¶
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 ¶
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:
- The worker was stopped via a call to worker.Done. You should not enqueue more work. The error will be ErrStopped.
- The incoming context was cancelled. You should probably not enqueue more work, but this is an application-specific decision. The error will be context.DeadlineExceeded or context.Canceled.
Never call Do from within a Do function because it will deadlock.
func (*Worker[T]) Done ¶
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.