Documentation
¶
Overview ¶
Package workerpool provides a worker pool for executing tasks concurrently with a fixed number of goroutines and bounded queue.
Basic usage:
pool, err := workerpool.NewSafe(4, 100)
if err != nil {
log.Fatal(err)
}
defer func() { <-pool.Shutdown() }()
task := workerpool.TaskFunc(func(ctx context.Context) error {
// Do work here
return nil
})
pool.Submit(task)
// Process results
result := <-pool.Results()
if result.Error != nil {
log.Printf("Task failed: %v", result.Error)
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// WorkerCount is the number of workers in the pool.
WorkerCount int
// QueueSize is the maximum number of tasks that can be queued.
// If 0, uses a reasonable default based on worker count.
QueueSize int
// TaskTimeout is the default timeout for individual task execution.
// Zero means no timeout.
TaskTimeout time.Duration
}
Config holds configuration options for creating a worker pool.
type Pool ¶
type Pool interface {
// Submit adds a task to the pool for execution.
// The task will be executed with context.Background().
// Use SubmitWithContext to provide a custom context.
Submit(task Task) error
// SubmitWithContext adds a task to the pool for execution with the given context.
// The context is passed to the task's Execute method, enabling timeout and
// cancellation propagation. If the pool has a TaskTimeout configured, the
// effective timeout will be the minimum of the context deadline and TaskTimeout.
SubmitWithContext(ctx context.Context, task Task) error
// Results returns a channel of task results.
Results() <-chan Result
// Shutdown initiates a graceful shutdown of the pool.
Shutdown() <-chan struct{}
// Size returns the number of workers in the pool.
Size() int
// QueueSize returns the current number of queued tasks.
QueueSize() int
}
Pool represents a worker pool that can execute tasks concurrently.
func NewSafe ¶
NewSafe creates a new worker pool with the specified number of workers and queue size. Returns an error if parameters are invalid instead of panicking.
func NewWithConfig
deprecated
func NewWithConfigSafe ¶
NewWithConfigSafe creates a new worker pool with the specified configuration. Returns an error if configuration is invalid instead of panicking.
type Result ¶
type Result struct {
// Task is the original task that was executed
Task Task
// Error is any error that occurred during task execution
Error error
// Duration is how long the task took to execute
Duration time.Duration
// WorkerID identifies which worker executed the task
WorkerID int
}
Result represents the result of a task execution.
Click to show internal directories.
Click to hide internal directories.