As mentioned in golang doc, sync is intent for low level library routines.
Other than the Once and WaitGroup types, most are intended for use by low-level library routines. Higher-level synchronization is better done via channels and communication.
I am not quite understanding this statement and I use sync like the example below.
My purpose is just to let main thread wait until all the other threads finish, similar to .join()
in c++ thread library.
Questions:
1: Is that proper to use sync like this? Or should I use channel instead of sync?
2: What is the difference between channel and sync?
var wg sync.WaitGroup // declare the variable globally
func send(a string, b string){
defer wg.Done()
// do something
}
func main(){
for i:=0; i<50; i++ {
wg.Add(1) // add delta
go send("1111", "2222")
}
wg.Wait() // wait until wg becomes 0
}
Any suggestions are appreciate! Thanks!