Lets say I have a list of 10 worker functions and I want 2 (or more) to be running at all times in parallel, advancing through the list when one finishes and then loop around and continue forever. So not to overload the server.
workers := make([]func(), 10)
for i := 0; i < 10; i++ {
workers[i] = createWorker()
}
func createWorker() func() {
return func() {
fmt.Println("I am working")
time.Sleep(time.Duration(rand.Intn(5)) * time.Second)
}
}
// My idea, keep sending workers to a buffered channel of size 2,
// so when one finishes it's no longer filled up and another worker is sent
workerChan := make(chan func(), 2)
go func() {
worker := <-workerChan
worker()
}()
for {
for _, worker := range workers {
workerChan <- worker
}
}
This runs the first worker function, and no more. Maybe the idea is correct and I need some guidance on how to implement it correctly.