This question already has an answer here:
I have this code to upload a maximum of 30 files at any given time (there could be thousands of files needing to be uploaded). Everything works exactly like I want it to: the goroutines take a file from the tasks, uploads it, and onto the next.
My question is: why don't the goroutines upload the same files? I've tested this and it seems like a file is never uploaded twice. Are the channels doing a round robin?
tasks := make(chan string, 10000)
var wg sync.WaitGroup
// create a limited number of routines
routineLimit := 30
for i := 0; i < routineLimit; i++ {
wg.Add(1)
go func() {
// check to see if there is a new task
for file := range tasks {
Upload(file) // upload the file
}
wg.Done()
}()
}
// get the files
files := GetFilePaths()
for _, file := range(files) {
// add the file to the queue of tasks
tasks <- file
}
wg.Wait()
</div>
When there are multiple receivers for a single channel as in your example, input will be received in a random order.