Sorry if this is a newb question but I'm a newb ;). I have the following playground. How do I create my goroutines dynamically? My first set in the playground works as expected but my second set returns "11" for each value. I can solve it by uncommenting line 38 but that seems kind of like a hack. Is there a more preferred way to create my goroutines dynamically?
package main
import (
"fmt"
"log"
"time"
)
func myFunc(i int) int {
return i
}
func first() {
firstChannel := make(chan int)
go func() { firstChannel <- myFunc(0) }()
go func() { firstChannel <- myFunc(1) }()
go func() { firstChannel <- myFunc(2) }()
go func() { firstChannel <- myFunc(3) }()
go func() { firstChannel <- myFunc(4) }()
go func() { firstChannel <- myFunc(5) }()
go func() { firstChannel <- myFunc(6) }()
go func() { firstChannel <- myFunc(7) }()
go func() { firstChannel <- myFunc(8) }()
go func() { firstChannel <- myFunc(9) }()
go func() { firstChannel <- myFunc(10) }()
for k := 0; k < 11; k++ {
select {
case result := <-firstChannel:
log.Println(result)
}
}
}
func second() {
secondChannel := make(chan int)
for j := 0; j < 11; j++ {
go func() { secondChannel <- myFunc(j) }()
//time.Sleep(1*time.Millisecond)
}
for k := 0; k < 11; k++ {
select {
case result := <-secondChannel:
log.Println(result)
}
}
}
func main() {
fmt.Println("First set------------------")
first()
time.Sleep(1 * time.Second)
fmt.Println("Second set------------------")
second()
}
Result:
First set------------------
2009/11/10 23:00:00 0
2009/11/10 23:00:00 1
2009/11/10 23:00:00 2
2009/11/10 23:00:00 3
2009/11/10 23:00:00 4
2009/11/10 23:00:00 5
2009/11/10 23:00:00 6
2009/11/10 23:00:00 7
2009/11/10 23:00:00 8
2009/11/10 23:00:00 9
2009/11/10 23:00:00 10
Second set------------------
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11
2009/11/10 23:00:01 11