github.com/network-quality/goresponsiveness@v0.0.0-20240129151524-343954285090/executor/executor.go (about) 1 package executor 2 3 import ( 4 "sync" 5 ) 6 7 type ExecutionMethod int 8 9 const ( 10 Parallel ExecutionMethod = iota 11 Serial 12 ) 13 14 type ExecutionUnit func() 15 16 func (ep ExecutionMethod) ToString() string { 17 switch ep { 18 case Parallel: 19 return "Parallel" 20 case Serial: 21 return "Serial" 22 } 23 return "Unrecognized execution method" 24 } 25 26 func Execute(executionMethod ExecutionMethod, executionUnits []ExecutionUnit) *sync.WaitGroup { 27 waiter := &sync.WaitGroup{} 28 29 // Make sure that we Add to the wait group all the execution units 30 // before starting to run any -- there is a potential race condition 31 // otherwise. 32 (*waiter).Add(len(executionUnits)) 33 34 for _, executionUnit := range executionUnits { 35 // Stupid capture in Go! Argh. 36 executionUnit := executionUnit 37 38 invoker := func() { 39 executionUnit() 40 (*waiter).Done() 41 } 42 switch executionMethod { 43 case Parallel: 44 go invoker() 45 case Serial: 46 invoker() 47 default: 48 panic("Invalid execution method value given.") 49 } 50 } 51 52 return waiter 53 }