Documentation ¶
Overview ¶
Package gowp provides a pool of workers with limited concurrency.
Example:
// create a pool for 10 tasks with 4 workers that is exists on error wp := gowp.New(context.TODO(), 10, 4, true) // add tasks to the pool for i := 0; i < 10; i++ { wp.Submit(func() error { // do something if i%2 == 0 { // return error if something happens return errors.New("error") } return nil }() } // signal that we are done producing work wp.Close() // wait for all the workers to finish their work, check the first error, if any if err := wp.Wait(); err != nil { // handle error }
Index ¶
Examples ¶
Constants ¶
const ( ErrPoolClosed = Error("pool is closed") ErrNoBuffer = Error("insufficient buffer") ErrInvalidSend = Error("work sent on closed pool") ErrNilTask = Error("task is nil") )
processing errors
const ( ErrInvalidBuffer = Error("buffer value should be greater than zero") ErrInvalidWorkerCnt = Error("worker count should be greater than zero") ErrNilContext = Error("context is nil") )
validation errors
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Option ¶
type Option func(o *config)
func WithContext ¶
WithContext returns an Option that sets the context for the pool. If the context is canceled the pool will be closed.
func WithExitOnError ¶
WithExitOnError returns an Option that sets the exitOnErr for the pool. If the exitOnErr is true, the pool will be closed when the first error is received.
func WithNumWorkers ¶
WithNumWorkers returns an Option that sets the number of workers for the pool. If the number of workers is less than or equal to zero, ErrInvalidWorkerCnt will be returned on Poll initialization.
type Pool ¶
type Pool struct {
// contains filtered or unexported fields
}
Pool represents a pool of workers that limits concurency as per the provided worker count.
Zero value is not usable. Use New() to create a new Pool.
Example (ExitOnError) ¶
ExitOnError demonstrates the use of a Worker Pool to implement a use-case where a task can fail and the pool should exit and return the error.
package main import ( "errors" "fmt" "time" "github.com/akshaybharambe14/gowp" ) func main() { const ( numJobs = 50 numWorkers = 2 closeOnErr = true ) wp, _ := gowp.New( numJobs, gowp.WithExitOnError(true), gowp.WithNumWorkers(numWorkers), ) for i := 0; i < numJobs; i++ { i := i _ = wp.Submit(func() error { fmt.Println("processing ", i) time.Sleep(time.Millisecond) if i == 2 { return errors.New("can't continue") } return nil }) } if err := wp.Wait(); err != nil { fmt.Println("process jobs: ", err) } }
Output: