├── go.mod ├── export_test.go ├── task.go ├── .github ├── workflows │ └── tests.yml └── renovate.json5 ├── example_test.go ├── .golangci.yml ├── README.md ├── workerpool.go ├── LICENSE └── workerpool_test.go /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cilium/workerpool 2 | 3 | go 1.22 4 | -------------------------------------------------------------------------------- /export_test.go: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright Authors of Cilium 3 | 4 | package workerpool 5 | 6 | // export for testing only 7 | 8 | // TasksCap returns the tasks channel capacity. 9 | func (wp *WorkerPool) TasksCap() int { 10 | return cap(wp.tasks) 11 | } 12 | -------------------------------------------------------------------------------- /task.go: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright Authors of Cilium 3 | 4 | package workerpool 5 | 6 | import ( 7 | "context" 8 | "fmt" 9 | ) 10 | 11 | // Task is a unit of work. 12 | type Task interface { 13 | // String returns the task identifier. 14 | fmt.Stringer 15 | // Err returns the error resulting from processing the 16 | // unit of work. 17 | Err() error 18 | } 19 | 20 | type task struct { 21 | run func(context.Context) error 22 | id string 23 | } 24 | 25 | type taskResult struct { 26 | err error 27 | id string 28 | } 29 | 30 | // Ensure that taskResult implements the Task interface. 31 | var _ Task = &taskResult{} 32 | 33 | // String implements fmt.Stringer for taskResult. 34 | func (t *taskResult) String() string { 35 | return t.id 36 | } 37 | 38 | // Err returns the error resulting from processing the taskResult. It ensures 39 | // that the taskResult struct implements the Task interface. 40 | func (t *taskResult) Err() error { 41 | return t.err 42 | } 43 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - v* 8 | pull_request: 9 | branches: 10 | - main 11 | - v* 12 | 13 | jobs: 14 | build: 15 | strategy: 16 | matrix: 17 | # Minimum required version per go.mod and latest two supported releases. 18 | go-version: ["1.22", "1.24", "1.25"] 19 | runs-on: ubuntu-latest 20 | steps: 21 | - name: Install Go 22 | uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0 23 | with: 24 | go-version: ${{ matrix.go-version }} 25 | - name: Checkout code 26 | uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 27 | - name: Run static checks 28 | uses: golangci/golangci-lint-action@e7fa5ac41e1cf5b7d48e45e42232ce7ada589601 # v9.1.0 29 | with: 30 | # renovate: datasource=github-releases depName=golangci/golangci-lint 31 | version: v2.6.2 32 | args: --config=.golangci.yml --verbose 33 | skip-cache: true 34 | - name: Build 35 | run: go build 36 | - name: Run unit tests 37 | run: go test -v -race -cover 38 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright Authors of Cilium 3 | 4 | package workerpool_test 5 | 6 | import ( 7 | "context" 8 | "fmt" 9 | "os" 10 | "runtime" 11 | 12 | "github.com/cilium/workerpool" 13 | ) 14 | 15 | // IsPrime returns true if n is prime, false otherwise. 16 | func IsPrime(n int64) bool { 17 | if n < 2 { 18 | return false 19 | } 20 | for p := int64(2); p*p <= n; p++ { 21 | if n%p == 0 { 22 | return false 23 | } 24 | } 25 | return true 26 | } 27 | 28 | func Example() { 29 | wp := workerpool.New(runtime.NumCPU()) 30 | for i, n := 0, int64(1_000_000_000_000_000_000); n < 1_000_000_000_000_000_100; i, n = i+1, n+1 { 31 | id := fmt.Sprintf("task #%d", i) 32 | // Use Submit to submit tasks for processing. Submit blocks when no 33 | // worker is available to pick up the task. 34 | err := wp.Submit(id, func(_ context.Context) error { 35 | fmt.Println("isprime", n) 36 | if IsPrime(n) { 37 | fmt.Println(n, "is prime!") 38 | } 39 | return nil 40 | }) 41 | // Submit fails when the pool is closed (ErrClosed) or being drained 42 | // (ErrDrained). Check for the error when appropriate. 43 | if err != nil { 44 | fmt.Fprintln(os.Stderr, err) 45 | return 46 | } 47 | } 48 | 49 | // Drain prevents submitting new tasks and blocks until all submitted tasks 50 | // complete. 51 | tasks, err := wp.Drain() 52 | if err != nil { 53 | fmt.Fprintln(os.Stderr, err) 54 | return 55 | } 56 | 57 | // Iterating over the results is useful if non-nil errors can be expected. 58 | for _, task := range tasks { 59 | // Err returns the error that the task returned after execution. 60 | if err := task.Err(); err != nil { 61 | fmt.Println("task", task, "failed:", err) 62 | } 63 | } 64 | 65 | // Close should be called once the worker pool is no longer necessary. 66 | if err := wp.Close(); err != nil { 67 | fmt.Fprintln(os.Stderr, err) 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /.golangci.yml: -------------------------------------------------------------------------------- 1 | # See https://golangci-lint.run/usage/configuration/ for available options. 2 | # Also https://github.com/cilium/cilium/blob/main/.golangci.yaml as a 3 | # reference. 4 | version: "2" 5 | linters: 6 | default: none 7 | enable: 8 | - asasalint 9 | - asciicheck 10 | - bidichk 11 | - bodyclose 12 | - containedctx 13 | - contextcheck 14 | - copyloopvar 15 | - cyclop 16 | - decorder 17 | - dogsled 18 | - dupl 19 | - dupword 20 | - durationcheck 21 | - err113 22 | - errcheck 23 | - errname 24 | - errorlint 25 | - exhaustive 26 | - exptostd 27 | - forcetypeassert 28 | - gocheckcompilerdirectives 29 | - gocognit 30 | - goconst 31 | - gocritic 32 | - godot 33 | - goheader 34 | - goprintffuncname 35 | - gosec 36 | - govet 37 | - grouper 38 | - ineffassign 39 | - interfacebloat 40 | - intrange 41 | - ireturn 42 | - makezero 43 | - mirror 44 | - misspell 45 | - musttag 46 | - nakedret 47 | - nestif 48 | - nilerr 49 | - nilnil 50 | - noctx 51 | - nosprintfhostport 52 | - perfsprint 53 | - prealloc 54 | - predeclared 55 | - reassign 56 | - revive 57 | - rowserrcheck 58 | - sloglint 59 | - staticcheck 60 | - tagalign 61 | - testifylint 62 | - thelper 63 | - tparallel 64 | - unconvert 65 | - unparam 66 | - unused 67 | - usestdlibvars 68 | - usetesting 69 | - wastedassign 70 | settings: 71 | goheader: 72 | template: |- 73 | SPDX-License-Identifier: Apache-2.0 74 | Copyright Authors of Cilium 75 | govet: 76 | enable-all: true 77 | perfsprint: 78 | strconcat: false 79 | sloglint: 80 | no-mixed-args: true 81 | static-msg: true 82 | no-global: "all" 83 | key-naming-case: kebab # be consistent with key names 84 | forbidden-keys: # let's no use reserved log keys 85 | - level 86 | - msg 87 | - source 88 | - time 89 | exclusions: 90 | rules: 91 | - linters: 92 | - cyclop 93 | path: (.+)_test\.go 94 | issues: 95 | # Maximum issues count per one linter. 96 | # Set to 0 to disable (default is 50) 97 | max-issues-per-linter: 0 98 | # Maximum count of issues with the same text. 99 | # Set to 0 to disable (default is 3) 100 | max-same-issues: 0 101 | fix: true # fix found issues (if it's supported by the linter). 102 | formatters: 103 | enable: 104 | - gofmt 105 | - goimports 106 | -------------------------------------------------------------------------------- /.github/renovate.json5: -------------------------------------------------------------------------------- 1 | { 2 | $schema: 'https://docs.renovatebot.com/renovate-schema.json', 3 | extends: [ 4 | 'config:recommended', 5 | ':gitSignOff', 6 | ':dependencyDashboard', 7 | 'helpers:pinGitHubActionDigests', 8 | ], 9 | prHourlyLimit: 8, 10 | prConcurrentLimit: 5, 11 | schedule: [ 12 | 'before 6am on monday', 13 | ], 14 | vulnerabilityAlerts: { 15 | enabled: true, 16 | schedule: [ 17 | 'at any time', 18 | ], 19 | labels: [ 20 | 'kind/security', 21 | 'release-blocker', 22 | 'release-note/security', 23 | ], 24 | }, 25 | stopUpdatingLabel: "renovate/stop-updating", 26 | keepUpdatedLabel: "renovate/keep-updated", 27 | baseBranchPatterns: [ 28 | 'main', 29 | ], 30 | postUpdateOptions: [ 31 | 'gomodTidy', 32 | ], 33 | packageRules: [ 34 | { 35 | groupName: 'all go module dependencies', 36 | matchFileNames: [ 37 | 'go.mod', 38 | 'go.sum', 39 | ], 40 | matchUpdateTypes: [ 41 | 'major', 42 | 'minor', 43 | 'digest', 44 | 'patch', 45 | 'pin', 46 | 'pinDigest', 47 | ], 48 | labels: [ 49 | 'area/vendor', 50 | 'enhancement', 51 | 'release-note/misc', 52 | ], 53 | }, 54 | { 55 | groupName: 'all github action dependencies', 56 | matchFileNames: [ 57 | '.github/workflows/**', 58 | ], 59 | matchUpdateTypes: [ 60 | 'major', 61 | 'minor', 62 | 'digest', 63 | 'patch', 64 | 'pin', 65 | 'pinDigest', 66 | ], 67 | labels: [ 68 | 'area/github-actions', 69 | 'enhancement', 70 | 'release-note/ci', 71 | ], 72 | }, 73 | { 74 | groupName: 'Go', 75 | matchDepNames: [ 76 | 'docker.io/library/golang', 77 | 'library/golang', 78 | 'go', 79 | 'golang', 80 | ], 81 | addLabels: [ 82 | 'area/build', 83 | 'release-note/misc', 84 | ], 85 | }, 86 | ], 87 | customManagers: [ 88 | { 89 | customType: "regex", 90 | description: "Match dependencies in github actions/workflows, with support for overriding the registryUrl, and extractVersion", 91 | managerFilePatterns: [ 92 | "/^.github/(?:workflows|actions|pr_deployment)/.+\\.ya?ml$/", 93 | ], 94 | matchStrings: [ 95 | "# renovate: datasource=(?.+?) depName=(?.+?)(?: packageName=(?.+?))?(?: registryUrl=(?.+?))?(?: depType=(?.+?))?(?: extractVersion=(?.+?))?(?: versioning=(?.+?))?\\s+.+?:\\s*[\"']?(?.+?)[\"']?\\s(.+?:\\s*[\"']?(?sha256:[a-f0-9]+)[\"']?\\s)?", 96 | ], 97 | }, 98 | ], 99 | } 100 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Workerpool 2 | 3 | [![Go Reference](https://pkg.go.dev/badge/github.com/cilium/workerpool.svg)](https://pkg.go.dev/github.com/cilium/workerpool) 4 | [![CI](https://github.com/cilium/workerpool/workflows/Tests/badge.svg)](https://github.com/cilium/workerpool/actions?query=workflow%3ATests) 5 | [![Go Report Card](https://goreportcard.com/badge/github.com/cilium/workerpool)](https://goreportcard.com/report/github.com/cilium/workerpool) 6 | 7 | Package workerpool implements a concurrency limiting worker pool. Worker 8 | routines are spawned on demand as tasks are submitted; up to the configured 9 | limit of concurrent workers. 10 | 11 | When the limit of concurrently running workers is reached, submitting a task 12 | blocks until a worker is able to pick it up. This behavior is intentional as it 13 | prevents from accumulating tasks which could grow unbounded. Therefore, it is 14 | the responsibility of the caller to queue up tasks if that's the intended 15 | behavior. 16 | 17 | One caveat is that while the number of concurrently running workers is limited, 18 | task results are not and they accumulate until they are collected. Therefore, 19 | if a large number of tasks can be expected, the workerpool should be 20 | periodically drained (e.g. every 10k tasks). 21 | 22 | This package is mostly useful when tasks are CPU bound and spawning too many 23 | routines would be detrimental to performance. It features a straightforward API 24 | and no external dependencies. See the section below for a usage example. 25 | 26 | ## Example 27 | 28 | ```go 29 | package main 30 | 31 | import ( 32 | "context" 33 | "fmt" 34 | "os" 35 | "runtime" 36 | 37 | "github.com/cilium/workerpool" 38 | ) 39 | 40 | // IsPrime returns true if n is prime, false otherwise. 41 | func IsPrime(n int64) bool { 42 | if n < 2 { 43 | return false 44 | } 45 | for p := int64(2); p*p <= n; p++ { 46 | if n%p == 0 { 47 | return false 48 | } 49 | } 50 | return true 51 | } 52 | 53 | func main() { 54 | wp := workerpool.New(runtime.NumCPU()) 55 | for i, n := 0, int64(1_000_000_000_000_000_000); n < 1_000_000_000_000_000_100; i, n = i+1, n+1 { 56 | id := fmt.Sprintf("task #%d", i) 57 | // Use Submit to submit tasks for processing. Submit blocks when no 58 | // worker is available to pick up the task. 59 | err := wp.Submit(id, func(_ context.Context) error { 60 | fmt.Println("isprime", n) 61 | if IsPrime(n) { 62 | fmt.Println(n, "is prime!") 63 | } 64 | return nil 65 | }) 66 | // Submit fails when the pool is closed (ErrClosed) or being drained 67 | // (ErrDrained). Check for the error when appropriate. 68 | if err != nil { 69 | fmt.Fprintln(os.Stderr, err) 70 | return 71 | } 72 | } 73 | 74 | // Drain prevents submitting new tasks and blocks until all submitted tasks 75 | // complete. 76 | tasks, err := wp.Drain() 77 | if err != nil { 78 | fmt.Fprintln(os.Stderr, err) 79 | return 80 | } 81 | 82 | // Iterating over the results is useful if non-nil errors can be expected. 83 | for _, task := range tasks { 84 | // Err returns the error that the task returned after execution. 85 | if err := task.Err(); err != nil { 86 | fmt.Println("task", task, "failed:", err) 87 | } 88 | } 89 | 90 | // Close should be called once the worker pool is no longer necessary. 91 | if err := wp.Close(); err != nil { 92 | fmt.Fprintln(os.Stderr, err) 93 | } 94 | } 95 | ``` 96 | -------------------------------------------------------------------------------- /workerpool.go: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright Authors of Cilium 3 | 4 | // Package workerpool implements a concurrency limiting worker pool. 5 | // Worker routines are spawned on demand as tasks are submitted; up to the 6 | // configured limit of concurrent workers. 7 | // 8 | // When the limit of concurrently running workers is reached, submitting a task 9 | // blocks until a worker is able to pick it up. This behavior is intentional as 10 | // it prevents from accumulating tasks which could grow unbounded. Therefore, 11 | // it is the responsibility of the caller to queue up tasks if that's the 12 | // intended behavior. 13 | // 14 | // One caveat is that while the number of concurrently running workers is 15 | // limited, task results are not and they accumulate until they are collected. 16 | // Therefore, if a large number of tasks can be expected, the workerpool should 17 | // be periodically drained (e.g. every 10k tasks). 18 | package workerpool 19 | 20 | import ( 21 | "context" 22 | "errors" 23 | "fmt" 24 | "sync" 25 | ) 26 | 27 | var ( 28 | // ErrDraining is returned when an operation is not possible because 29 | // draining is in progress. 30 | ErrDraining = errors.New("drain operation in progress") 31 | // ErrClosed is returned when operations are attempted after a call to Close. 32 | ErrClosed = errors.New("worker pool is closed") 33 | ) 34 | 35 | // WorkerPool spawns, on demand, a number of worker routines to process 36 | // submitted tasks concurrently. The number of concurrent routines never 37 | // exceeds the specified limit. 38 | type WorkerPool struct { 39 | workers chan struct{} 40 | tasks chan *task 41 | cancel context.CancelFunc 42 | results []Task 43 | wg sync.WaitGroup 44 | 45 | mu sync.Mutex 46 | draining bool 47 | closed bool 48 | } 49 | 50 | // New creates a new pool of workers where at most n workers process submitted 51 | // tasks concurrently. New panics if n ≤ 0. 52 | func New(n int) *WorkerPool { 53 | return NewWithContext(context.Background(), n) 54 | } 55 | 56 | // NewWithContext creates a new pool of workers where at most n workers process submitted 57 | // tasks concurrently. New panics if n ≤ 0. The context is used as the parent context to the context of the task func passed to Submit. 58 | func NewWithContext(ctx context.Context, n int) *WorkerPool { 59 | if n <= 0 { 60 | panic(fmt.Sprintf("workerpool.New: n must be > 0, got %d", n)) 61 | } 62 | wp := &WorkerPool{ 63 | workers: make(chan struct{}, n), 64 | tasks: make(chan *task), 65 | } 66 | ctx, cancel := context.WithCancel(ctx) 67 | wp.cancel = cancel 68 | go wp.run(ctx) 69 | return wp 70 | } 71 | 72 | // Cap returns the concurrent workers capacity, see New(). 73 | func (wp *WorkerPool) Cap() int { 74 | return cap(wp.workers) 75 | } 76 | 77 | // Len returns the count of concurrent workers currently running. 78 | func (wp *WorkerPool) Len() int { 79 | return len(wp.workers) 80 | } 81 | 82 | // Submit submits f for processing by a worker. The given id is useful for 83 | // identifying the task once it is completed. The task f must return when the 84 | // context ctx is cancelled. The context passed to task f is cancelled when 85 | // Close is called. 86 | // 87 | // Submit blocks until a routine start processing the task. 88 | // 89 | // If a drain operation is in progress, ErrDraining is returned and the task 90 | // is not submitted for processing. 91 | // If the worker pool is closed, ErrClosed is returned and the task is not 92 | // submitted for processing. 93 | func (wp *WorkerPool) Submit(id string, f func(ctx context.Context) error) error { 94 | wp.mu.Lock() 95 | if wp.closed { 96 | wp.mu.Unlock() 97 | return ErrClosed 98 | } 99 | if wp.draining { 100 | wp.mu.Unlock() 101 | return ErrDraining 102 | } 103 | wp.wg.Add(1) 104 | wp.mu.Unlock() 105 | wp.tasks <- &task{ 106 | id: id, 107 | run: f, 108 | } 109 | return nil 110 | } 111 | 112 | // Drain waits until all tasks are completed. This operation prevents 113 | // submitting new tasks to the worker pool. Drain returns the results of the 114 | // tasks that have been processed. 115 | // If a drain operation is already in progress, ErrDraining is returned. 116 | // If the worker pool is closed, ErrClosed is returned. 117 | func (wp *WorkerPool) Drain() ([]Task, error) { 118 | wp.mu.Lock() 119 | if wp.closed { 120 | wp.mu.Unlock() 121 | return nil, ErrClosed 122 | } 123 | if wp.draining { 124 | wp.mu.Unlock() 125 | return nil, ErrDraining 126 | } 127 | wp.draining = true 128 | wp.mu.Unlock() 129 | 130 | wp.wg.Wait() 131 | 132 | // NOTE: It's not necessary to hold a lock when reading or writing 133 | // wp.results as no other routine is running at this point besides the 134 | // "run" routine which should be waiting on the tasks channel. 135 | res := wp.results 136 | wp.results = nil 137 | 138 | wp.mu.Lock() 139 | wp.draining = false 140 | wp.mu.Unlock() 141 | 142 | return res, nil 143 | } 144 | 145 | // Close closes the worker pool, rendering it unable to process new tasks. 146 | // Close sends the cancellation signal to any running task and waits for all 147 | // workers, if any, to return. 148 | // Close will return ErrClosed if it has already been called. 149 | func (wp *WorkerPool) Close() error { 150 | wp.mu.Lock() 151 | if wp.closed { 152 | wp.mu.Unlock() 153 | return ErrClosed 154 | } 155 | wp.closed = true 156 | wp.mu.Unlock() 157 | 158 | wp.cancel() 159 | wp.wg.Wait() 160 | 161 | // At this point, all routines have returned. This means that Submit is not 162 | // pending to write to the task channel and it is thus safe to close it. 163 | close(wp.tasks) 164 | 165 | // wait for the "run" routine 166 | <-wp.workers 167 | return nil 168 | } 169 | 170 | // run loops over the tasks channel and starts processing routines. It should 171 | // only be called once during the lifetime of a WorkerPool. 172 | func (wp *WorkerPool) run(ctx context.Context) { 173 | for t := range wp.tasks { 174 | 175 | result := taskResult{id: t.id} 176 | wp.results = append(wp.results, &result) 177 | wp.workers <- struct{}{} 178 | go func() { 179 | defer wp.wg.Done() 180 | if t.run != nil { 181 | result.err = t.run(ctx) 182 | } 183 | <-wp.workers 184 | }() 185 | } 186 | close(wp.workers) 187 | } 188 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} Authors of Cilium 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /workerpool_test.go: -------------------------------------------------------------------------------- 1 | // SPDX-License-Identifier: Apache-2.0 2 | // Copyright Authors of Cilium 3 | 4 | package workerpool_test 5 | 6 | import ( 7 | "context" 8 | "errors" 9 | "fmt" 10 | "runtime" 11 | "sync" 12 | "testing" 13 | "time" 14 | 15 | "github.com/cilium/workerpool" 16 | ) 17 | 18 | func TestWorkerPoolNewPanics(t *testing.T) { 19 | // helper expecting New(n) to panic. 20 | testWorkerPoolNewPanics := func(n int) { 21 | defer func() { 22 | if r := recover(); r == nil { 23 | t.Errorf("New(%d) should panic()", n) 24 | } 25 | }() 26 | _ = workerpool.New(n) 27 | } 28 | 29 | testWorkerPoolNewPanics(0) 30 | testWorkerPoolNewPanics(-1) 31 | } 32 | 33 | func TestWorkerPoolTasksCapacity(t *testing.T) { 34 | wp := workerpool.New(runtime.NumCPU()) 35 | defer func() { 36 | if err := wp.Close(); err != nil { 37 | t.Errorf("close: got '%v', want no error", err) 38 | } 39 | }() 40 | 41 | if c := wp.TasksCap(); c != 0 { 42 | t.Errorf("tasks channel capacity is %d; want 0 (an unbuffered channel)", c) 43 | } 44 | } 45 | 46 | func TestWorkerPoolCap(t *testing.T) { 47 | one := workerpool.New(1) 48 | defer func() { 49 | if err := one.Close(); err != nil { 50 | t.Errorf("close: got '%v', want no error", err) 51 | } 52 | }() 53 | if c := one.Cap(); c != 1 { 54 | t.Errorf("got %d; want %d", c, 1) 55 | } 56 | 57 | n := runtime.NumCPU() 58 | ncpu := workerpool.New(n) 59 | defer func() { 60 | if err := ncpu.Close(); err != nil { 61 | t.Errorf("close: got '%v', want no error", err) 62 | } 63 | }() 64 | if c := ncpu.Cap(); c != n { 65 | t.Errorf("got %d; want %d", c, n) 66 | } 67 | 68 | fortyTwo := workerpool.New(42) 69 | defer func() { 70 | if err := fortyTwo.Close(); err != nil { 71 | t.Errorf("close: got '%v', want no error", err) 72 | } 73 | }() 74 | if c := fortyTwo.Cap(); c != 42 { 75 | t.Errorf("got %d; want %d", c, 42) 76 | } 77 | } 78 | 79 | func TestWorkerPoolLen(t *testing.T) { 80 | wp := workerpool.New(1) 81 | if l := wp.Len(); l != 0 { 82 | t.Errorf("got %d; want %d", l, 0) 83 | } 84 | 85 | submitted := make(chan struct{}) 86 | err := wp.Submit("", func(ctx context.Context) error { 87 | close(submitted) 88 | <-ctx.Done() 89 | return ctx.Err() 90 | }) 91 | if err != nil { 92 | t.Fatalf("failed to submit task: %v", err) 93 | } 94 | 95 | <-submitted 96 | if l := wp.Len(); l != 1 { 97 | t.Errorf("got %d; want %d", l, 1) 98 | } 99 | 100 | if err := wp.Close(); err != nil { 101 | t.Fatalf("close: got '%v', want no error", err) 102 | } 103 | if l := wp.Len(); l != 0 { 104 | t.Errorf("got %d; want %d", l, 0) 105 | } 106 | } 107 | 108 | // TestWorkerPoolConcurrentTasksCount ensure that there is at least, but no 109 | // more than n workers running in the pool when more than n tasks are 110 | // submitted. 111 | func TestWorkerPoolConcurrentTasksCount(t *testing.T) { 112 | n := runtime.NumCPU() 113 | wp := workerpool.New(n) 114 | defer func() { 115 | if err := wp.Close(); err != nil { 116 | t.Errorf("close: got '%v', want no error", err) 117 | } 118 | }() 119 | 120 | // working is written to by each task as soon as possible. 121 | working := make(chan struct{}) 122 | // NOTE: schedule one more task than we have workers, hence n+1. 123 | for i := range n + 1 { 124 | id := fmt.Sprintf("task #%2d", i) 125 | err := wp.Submit(id, func(ctx context.Context) error { 126 | select { 127 | case working <- struct{}{}: 128 | case <-ctx.Done(): 129 | return ctx.Err() 130 | } 131 | <-ctx.Done() 132 | return nil 133 | }) 134 | if err != nil { 135 | t.Fatalf("failed to submit task '%s': %v", id, err) 136 | } 137 | } 138 | 139 | // ensure that n workers are busy. 140 | for i := range n { 141 | select { 142 | case <-working: 143 | case <-time.After(100 * time.Millisecond): 144 | t.Fatalf("got %d tasks running; want %d", i, n) 145 | } 146 | } 147 | 148 | // ensure that one task is not scheduled, as all workers should now be 149 | // waiting on the context. 150 | select { 151 | case <-working: 152 | t.Fatalf("got %d tasks running; want %d", n+1, n) 153 | case <-time.After(100 * time.Millisecond): 154 | } 155 | } 156 | 157 | func TestWorkerPool(t *testing.T) { 158 | n := runtime.NumCPU() 159 | wp := workerpool.New(n) 160 | 161 | numTasks := n + 2 162 | done := make(chan struct{}) 163 | // working is used to ensure that n routines are dispatched at a given time 164 | working := make(chan struct{}) 165 | var wg sync.WaitGroup 166 | wg.Add(numTasks - 1) 167 | for i := range numTasks - 1 { 168 | id := fmt.Sprintf("task #%2d", i) 169 | err := wp.Submit(id, func(_ context.Context) error { 170 | defer wg.Done() 171 | working <- struct{}{} 172 | done <- struct{}{} 173 | return nil 174 | }) 175 | if err != nil { 176 | t.Errorf("failed to submit task '%s': %v", id, err) 177 | } 178 | } 179 | 180 | // ensure n workers are busy 181 | for range n { 182 | <-working 183 | } 184 | 185 | // the n workers are busy so submitting a new task should block 186 | ready := make(chan struct{}) 187 | sc := make(chan struct{}) 188 | wg.Add(1) 189 | go func() { 190 | id := fmt.Sprintf("task #%2d", numTasks-1) 191 | ready <- struct{}{} 192 | err := wp.Submit(id, func(_ context.Context) error { 193 | defer wg.Done() 194 | done <- struct{}{} 195 | return nil 196 | }) 197 | if err != nil { 198 | t.Errorf("failed to submit task '%s': %v", id, err) 199 | } 200 | sc <- struct{}{} 201 | }() 202 | 203 | <-ready 204 | select { 205 | case <-sc: 206 | t.Errorf("submit should be blocking") 207 | case <-time.After(100 * time.Millisecond): 208 | } 209 | 210 | wg.Add(1) 211 | go func() { 212 | defer wg.Done() 213 | ready <- struct{}{} 214 | results, err := wp.Drain() 215 | if err != nil { 216 | t.Errorf("draining failed: %v", err) 217 | } 218 | if len(results) != numTasks { 219 | t.Errorf("missing tasks results: got '%d', want '%d'", len(results), numTasks) 220 | } 221 | for i, r := range results { 222 | id := fmt.Sprintf("task #%2d", i) 223 | if s := r.String(); s != id { 224 | t.Errorf("String: got '%s', want '%s'", s, id) 225 | } 226 | if err := r.Err(); err != nil { 227 | t.Errorf("Err: got '%v', want no error", err) 228 | } 229 | } 230 | }() 231 | 232 | <-ready 233 | // un-block the worker routines 234 | for range numTasks - 1 { 235 | <-done 236 | } 237 | // The last task was blocked in wp.run() and not yet scheduled on a worker. 238 | // Now that some workers are free, the task should have been picked up. 239 | <-working 240 | <-done 241 | 242 | wg.Wait() 243 | 244 | if err := wp.Close(); err != nil { 245 | t.Errorf("close: got '%v', want no error", err) 246 | } 247 | } 248 | 249 | func TestConcurrentDrain(t *testing.T) { 250 | n := runtime.NumCPU() 251 | wp := workerpool.New(n) 252 | 253 | numTasks := n + 1 254 | done := make(chan struct{}) 255 | var wg sync.WaitGroup 256 | wg.Add(numTasks) 257 | for i := range numTasks { 258 | id := fmt.Sprintf("task #%2d", i) 259 | err := wp.Submit(id, func(_ context.Context) error { 260 | defer wg.Done() 261 | done <- struct{}{} 262 | return nil 263 | }) 264 | if err != nil { 265 | t.Errorf("failed to submit task '%s': %v", id, err) 266 | } 267 | } 268 | 269 | wg.Add(1) 270 | ready := make(chan struct{}) 271 | go func() { 272 | defer wg.Done() 273 | ready <- struct{}{} 274 | results, err := wp.Drain() 275 | if err != nil { 276 | t.Errorf("draining failed: %v", err) 277 | } 278 | if len(results) != numTasks { 279 | t.Errorf("missing tasks results: got '%d', want '%d'", len(results), numTasks) 280 | } 281 | for i, r := range results { 282 | id := fmt.Sprintf("task #%2d", i) 283 | if s := r.String(); s != id { 284 | t.Errorf("String: got '%s', want '%s'", s, id) 285 | } 286 | if err := r.Err(); err != nil { 287 | t.Errorf("Err: got '%v', want no error", err) 288 | } 289 | } 290 | }() 291 | 292 | // make sure that drain is already called by the other routine 293 | <-ready 294 | time.Sleep(10 * time.Millisecond) 295 | 296 | if err := wp.Submit("", nil); !errors.Is(err, workerpool.ErrDraining) { 297 | t.Errorf("submit: got '%v', want '%v'", err, workerpool.ErrDraining) 298 | } 299 | 300 | results, err := wp.Drain() 301 | if !errors.Is(err, workerpool.ErrDraining) { 302 | t.Errorf("drain: got '%v', want '%v'", err, workerpool.ErrDraining) 303 | } 304 | if results != nil { 305 | t.Errorf("drain: got '%v', want '%v'", results, nil) 306 | } 307 | 308 | // un-block the worker routines to allow the test to complete 309 | for range numTasks { 310 | <-done 311 | } 312 | 313 | wg.Wait() 314 | 315 | results, err = wp.Drain() 316 | if err != nil { 317 | t.Errorf("drain: got '%v', want '%v'", err, nil) 318 | } 319 | if len(results) != 0 { 320 | t.Errorf("drain: unexpectedly got '%d' results", len(results)) 321 | } 322 | 323 | if err := wp.Close(); err != nil { 324 | t.Errorf("close: got '%v', want no error", err) 325 | } 326 | } 327 | 328 | func TestWorkerPoolDrainAfterClose(t *testing.T) { 329 | wp := workerpool.New(runtime.NumCPU()) 330 | if err := wp.Close(); err != nil { 331 | t.Fatalf("close: got '%v', want no error", err) 332 | } 333 | tasks, err := wp.Drain() 334 | if !errors.Is(err, workerpool.ErrClosed) { 335 | t.Errorf("got %v; want %v", err, workerpool.ErrClosed) 336 | } 337 | if tasks != nil { 338 | t.Errorf("got %v as tasks; want %v", tasks, nil) 339 | } 340 | } 341 | 342 | func TestWorkerPoolSubmitNil(t *testing.T) { 343 | wp := workerpool.New(runtime.NumCPU()) 344 | defer func() { 345 | if err := wp.Close(); err != nil { 346 | t.Errorf("close: got '%v', want no error", err) 347 | } 348 | }() 349 | id := "nothing" 350 | if err := wp.Submit(id, nil); err != nil { 351 | t.Fatalf("got %v; want no error", err) 352 | } 353 | tasks, err := wp.Drain() 354 | if err != nil { 355 | t.Errorf("got %v; want no error", err) 356 | } 357 | if n := len(tasks); n != 1 { 358 | t.Errorf("got %v tasks; want 1", n) 359 | } 360 | r := tasks[0] 361 | if s := r.String(); s != id { 362 | t.Errorf("String: got '%s', want '%s'", s, id) 363 | } 364 | if err := r.Err(); err != nil { 365 | t.Errorf("Err: got '%v', want no error", err) 366 | } 367 | 368 | } 369 | 370 | func TestWorkerPoolSubmitAfterClose(t *testing.T) { 371 | wp := workerpool.New(runtime.NumCPU()) 372 | if err := wp.Close(); err != nil { 373 | t.Fatalf("close: got '%v', want no error", err) 374 | } 375 | if err := wp.Submit("dummy", nil); !errors.Is(err, workerpool.ErrClosed) { 376 | t.Fatalf("got %v; want %v", err, workerpool.ErrClosed) 377 | } 378 | } 379 | 380 | func TestWorkerPoolManyClose(t *testing.T) { 381 | wp := workerpool.New(runtime.NumCPU()) 382 | 383 | // first call to Close() should not return an error. 384 | if err := wp.Close(); err != nil { 385 | t.Fatalf("unexpected error on Close(): %s", err) 386 | } 387 | 388 | // calling Close() more than once should always return an error. 389 | if err := wp.Close(); !errors.Is(err, workerpool.ErrClosed) { 390 | t.Fatalf("got %v; want %v", err, workerpool.ErrClosed) 391 | } 392 | if err := wp.Close(); !errors.Is(err, workerpool.ErrClosed) { 393 | t.Fatalf("got %v; want %v", err, workerpool.ErrClosed) 394 | } 395 | } 396 | 397 | func TestWorkerPoolClose(t *testing.T) { 398 | n := runtime.NumCPU() 399 | wp := workerpool.New(n) 400 | 401 | // working is written to by each task as soon as possible. 402 | working := make(chan struct{}) 403 | var wg sync.WaitGroup 404 | wg.Add(n) 405 | for i := range n { 406 | id := fmt.Sprintf("task #%2d", i) 407 | err := wp.Submit(id, func(ctx context.Context) error { 408 | working <- struct{}{} 409 | <-ctx.Done() 410 | wg.Done() 411 | return ctx.Err() 412 | }) 413 | if err != nil { 414 | t.Errorf("failed to submit task '%s': %v", id, err) 415 | } 416 | } 417 | 418 | // ensure n workers are busy 419 | for range n { 420 | <-working 421 | } 422 | 423 | if err := wp.Close(); err != nil { 424 | t.Errorf("close: got '%v', want no error", err) 425 | } 426 | wg.Wait() // all routines should have returned 427 | } 428 | 429 | func TestWorkerPoolNewWithContext(t *testing.T) { 430 | ctx, cancel := context.WithCancel(context.Background()) 431 | n := runtime.NumCPU() 432 | wp := workerpool.NewWithContext(ctx, n) 433 | 434 | // working is written to by each task as soon as possible. 435 | working := make(chan struct{}) 436 | var wg sync.WaitGroup 437 | // Create n tasks waiting on the context to be cancelled. 438 | wg.Add(n) 439 | for i := range n { 440 | id := fmt.Sprintf("task #%2d", i) 441 | err := wp.Submit(id, func(ctx context.Context) error { 442 | working <- struct{}{} 443 | <-ctx.Done() 444 | wg.Done() 445 | return ctx.Err() 446 | }) 447 | if err != nil { 448 | t.Errorf("failed to submit task '%s': %v", id, err) 449 | } 450 | } 451 | 452 | // ensure n workers are busy 453 | for range n { 454 | <-working 455 | } 456 | 457 | // cancel the parent context, which should complete all tasks. 458 | cancel() 459 | wg.Wait() 460 | 461 | // Submitting a task once the parent context has been cancelled should 462 | // succeed and give a cancelled context to the task. This is not ideal and 463 | // might change in the future. 464 | wg.Add(1) 465 | id := "last" 466 | err := wp.Submit(id, func(ctx context.Context) error { 467 | defer wg.Done() 468 | select { 469 | case <-ctx.Done(): 470 | default: 471 | t.Errorf("last task expected context to be cancelled") 472 | } 473 | return nil 474 | }) 475 | if err != nil { 476 | t.Errorf("failed to submit task '%s': %v", id, err) 477 | } 478 | 479 | wg.Wait() 480 | 481 | if err := wp.Close(); err != nil { 482 | t.Errorf("close: got '%v', want no error", err) 483 | } 484 | } 485 | --------------------------------------------------------------------------------