It's not enough to add a "return" statement after "с <- chnum". That's because the channel will block until the information can be inserted in the channel. Also, you need to consider that you might need a buffered channel so multiple entries can be inserted and retrieved from your threads. Consider the code below, which uses buffered channels:
package main
import "fmt"
func main() {
numGoRountines := 10
c := make(chan int, numGoRountines)
for i := 0; i < numGoRountines; i++ {
go myRoutine(i, c)
}
for i := 0; i < numGoRountines; i++ {
fmt.Println("Returned routine:", <-c)
}
}
func myRoutine(chnum int, c chan int) {
//doing some stuff here
c <- chnum
//and doing some stuff here
}
Possible output:
Returned routine: 9
Returned routine: 0
Returned routine: 1
Returned routine: 2
Returned routine: 3
Returned routine: 4
Returned routine: 5
Returned routine: 6
Returned routine: 7
Returned routine: 8
Regarding your second question, go will clean those extra goroutines for you. But be aware that if the parent dies, the child threads dies as well. You can see an example below:
package main
import (
"fmt"
"sync"
)
func main() {
var waitGroupOnlyForParents sync.WaitGroup
numGoRountines := 4
for i := 0; i < numGoRountines; i++ {
waitGroupOnlyForParents.Add(1)
go myRoutine(&waitGroupOnlyForParents, i)
}
// makes main function waits for every one who calls the method Done() in our wait group
waitGroupOnlyForParents.Wait()
}
func myRoutine(wg *sync.WaitGroup, myId int) {
defer wg.Done()
numGoRountines := 2
for i := 0; i < numGoRountines; i++ {
go anotherRoutine(myId, i)
}
}
func anotherRoutine( parentId, childId int){
fmt.Printf("Created by %d, my name is %d
", parentId, childId)
}
possible output:
Created by 3, my name is 1
Created by 0, my name is 1
Created by 1, my name is 1
Now suppose we wish to sync all threads, to make sure each of them does everything they need we change the code slightly to this:
package main
import (
"fmt"
"sync"
)
func main() {
var waitGroupForAllThreads sync.WaitGroup
numGoRountines := 4
for i := 0; i < numGoRountines; i++ {
waitGroupForAllThreads.Add(1)
go myRoutine(&waitGroupForAllThreads, i)
}
// makes main function waits for every one who calls the method Done() in our wait group
waitGroupForAllThreads.Wait()
}
func myRoutine(wg *sync.WaitGroup, myId int) {
defer wg.Done()
numGoRountines := 2
for i := 0; i < numGoRountines; i++ {
wg.Add(1)
go anotherRoutine(wg, myId, i)
}
}
func anotherRoutine(wg *sync.WaitGroup, parentId, childId int){
defer wg.Done()
fmt.Printf("Created by %d, my name is %d
", parentId, childId)
}
possible output (in this case all prints will for sure be displayed, the order may change):
Created by 3, my name is 1
Created by 0, my name is 1
Created by 1, my name is 1
Created by 2, my name is 1
Created by 3, my name is 0
Created by 0, my name is 0
Created by 1, my name is 0
Created by 2, my name is 0