github.com/Cloud-Foundations/Dominator@v0.3.4/lib/concurrent/api.go (about) 1 /* 2 Package concurrent provides a simple way to run functions concurrently and 3 then reap the results. 4 5 Package concurrent allows cuncurrent running of provided functions, by 6 default limiting the parallelism to the number of CPUs. The functions return 7 an error value and these may be reaped at the end. 8 */ 9 package concurrent 10 11 type nilPutter struct{} 12 13 type putter interface { 14 put() 15 } 16 17 // State maintains state needed to manage running functions concurrently. 18 type State struct { 19 entered bool 20 error error 21 errorChannel chan error 22 pending uint64 23 putter putter 24 reaped bool 25 semaphore chan struct{} 26 } 27 28 // NewState returns a new State. 29 func NewState(numConcurrent uint) *State { 30 return newState(numConcurrent, &nilPutter{}) 31 } 32 33 func NewStateWithLinearConcurrencyIncrease(initialNumConcurrent uint, 34 maximumNumConcurrent uint) *State { 35 return newStateWithLinearConcurrencyIncrease(initialNumConcurrent, 36 maximumNumConcurrent) 37 } 38 39 // GoRun will run the provided function in a goroutine. If the function returns 40 // a non-nil error, this will be returned in a future call to GoRun or by 41 // Reap. GoRun cannot be called concurrently with GoRun or Reap. 42 func (state *State) GoRun(doFunc func() error) error { 43 return state.goRun(doFunc) 44 } 45 46 // Reap returns the first error encountered by the functions and waits for 47 // remaining functions to complete. The State can no longer be used after Reap. 48 func (state *State) Reap() error { 49 if state.entered { 50 panic("GoRun is running") 51 } 52 return state.reap() 53 }