NewWorkerPool creates a new WorkerPool with the provided configuration.
(cfg Config[T])
| 236 | |
| 237 | // NewWorkerPool creates a new WorkerPool with the provided configuration. |
| 238 | func NewWorkerPool[T any](cfg Config[T]) WorkerPool[T] { |
| 239 | if cfg.WorkerIdleTimeout == 0 { |
| 240 | cfg.WorkerIdleTimeout = defaultWorkerIdleTimeout |
| 241 | } |
| 242 | // We treat 0 as being default initialized, and use the defaults. |
| 243 | if cfg.MinWorkers == 0 { |
| 244 | cfg.MinWorkers = defaultMinWorkers |
| 245 | } |
| 246 | // We treat negative values as explicitly disabling the minimum number of workers. |
| 247 | if cfg.MinWorkers < 0 { |
| 248 | cfg.MinWorkers = 0 |
| 249 | } |
| 250 | if cfg.MaxWorkers <= 0 { |
| 251 | cfg.MaxWorkers = defaultMaxWorkers |
| 252 | } |
| 253 | // We treat 0 as being default initialized, and use the defaults. |
| 254 | if cfg.QueueSize == 0 { |
| 255 | cfg.QueueSize = defaultQueueSize |
| 256 | } |
| 257 | // We treat negative values as explicitly disabling the queue. |
| 258 | if cfg.QueueSize < 0 { |
| 259 | cfg.QueueSize = 0 |
| 260 | } |
| 261 | if cfg.MinWorkers > cfg.MaxWorkers { |
| 262 | cfg.MaxWorkers = cfg.MinWorkers |
| 263 | } |
| 264 | |
| 265 | wp := &workerPool[T]{ |
| 266 | Config: cfg, |
| 267 | |
| 268 | mainQueue: make(chan *contextualItem[T], cfg.QueueSize), |
| 269 | fastQueue: make(chan *contextualItem[T]), |
| 270 | } |
| 271 | |
| 272 | for i := 0; i < wp.MinWorkers; i++ { |
| 273 | wp.spawnWorker(nil) |
| 274 | } |
| 275 | |
| 276 | return wp |
| 277 | } |
| 278 | |
| 279 | func incrementIfSmallerThan(i *int32, max int32) bool { |
| 280 | for v := atomic.LoadInt32(i); v < max; v = atomic.LoadInt32(i) { |