-2

I'm tying to execute things async with multiple go routines. I pass in the number of "threads" to use to process.

func refresh() {
    sign := make(chan int, len(allSets))
    for _, set := range allSets {
        i := int(set.GetId())
        if statement {
            // Update
            go UpdateKeywordSearcher(i, sign)
        }
    }

    // for this part, I wanna call some func after above all for..loop UpdateKeywordSearcher done
    // call anotherFunc()
} 
    
func UpdateKeywordSearcher(setid int, sign chan int) {
   // do some update logic
   sign <- setid
}

as above written codes, how can I call another method after all multiple go routine finished? I searched for select but don't know what exactly I should write.

Jem Tucker
  • 1,143
  • 16
  • 35
Frank
  • 977
  • 3
  • 14
  • 35
  • 10
    A `sync.WaitGroup` may be a better choice here, see [Prevent the main() function from terminating before goroutines finish in Golang](https://stackoverflow.com/questions/42752705/prevent-the-main-function-from-terminating-before-goroutines-finish-in-golang/42753005#42753005). – icza Nov 02 '20 at 11:04

1 Answers1

0

As others have suggested, a sync.WaitGroup is probably the most sensible thing to use here. That said, you can do what you want to achieve by reading the right number of items of the signal channel.

For example (I've simplified your example a bit but this should give you the idea):

package main

func main() {
    allSets := []int{1,2,3,4,5,6}
    sign := make(chan int)
    
    for _, id := range allSets {
        go UpdateKeywordSearcher(id, sign)
    }
    
    for i := 0; i < len(allSets); i++ {
        <-sign
    }
    
    close(sign) // Close the channel now we are done with it
    
    println("Done")
}
    
func UpdateKeywordSearcher(setid int, sign chan int) {
    // do some update logic
    sign <- setid
}
Jem Tucker
  • 1,143
  • 16
  • 35