k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/measurement/util/workerqueue/workerqueue.go (about) 1 /* 2 Copyright 2019 The Kubernetes Authors. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package workerqueue 18 19 import ( 20 "k8s.io/apimachinery/pkg/util/wait" 21 "k8s.io/client-go/util/workqueue" 22 ) 23 24 // Interface of a workerqueue. 25 type Interface interface { 26 Add(*func()) 27 Stop() 28 } 29 30 // WorkerQueue is worker group with a task queue. 31 type WorkerQueue struct { 32 queue workqueue.Interface 33 workerGroup wait.Group 34 } 35 36 // NewWorkerQueue creates new WorkerQueue 37 // with worker group of given size. 38 func NewWorkerQueue(size int) Interface { 39 wq := &WorkerQueue{ 40 queue: workqueue.New(), 41 } 42 for i := 0; i < size; i++ { 43 wq.workerGroup.Start(wq.worker) 44 } 45 return wq 46 } 47 48 // Add adds a new task to the queue. 49 func (wq *WorkerQueue) Add(f *func()) { 50 wq.queue.Add(f) 51 } 52 53 // Stop stops the working group. 54 func (wq *WorkerQueue) Stop() { 55 wq.queue.ShutDown() 56 wq.workerGroup.Wait() 57 } 58 59 func (wq *WorkerQueue) worker() { 60 for { 61 f, stop := wq.queue.Get() 62 if stop { 63 return 64 } 65 (*f.(*func()))() 66 wq.queue.Done(f) 67 } 68 }