I am learning Go. I have a for loop with recursive steps until several things (unknown quantity) are found among an unknown quantity of items. I want to use the go func()
to be able to speed up the search. I am using the chan
and chan <-
<-chan
to monitor the workers. However I dont know how to wait for the job to be done and be able to use the found items.
Thank you !
Wait groups are useful here.
Declare a variable and add a wait group:
var wg sync.WaitGroup
wg.Add(1)
Defer the wait group finishing inside your go routine and block outside it:
go func(){
//your function here. If you want a for loop with go routines put it outside the go routine
defer wg.Done()
}()
wg.Wait()
The other answer is correct about the sync.WaitGroup
is the tool to use here. The for
loop IMHO is misplaced, I think you are about to process items in a loop concurrently; like this:
func main() {
wg := &sync.WaitGroup{}
for item := range sourceOfUnknownQuantity {
wg.Add(1)
go process(item, wg)
}
wg.Wait()
}
func process(item int, wg *sync.WaitGroup) {
defer wg.Done()
// process item
}
var (
sourceOfUnknownQuantity = make(chan int)
)
Using sourceOfUnknownQuantity
in the for
loop is just for demonstration. Your implementation of loop might differ.