Created
August 23, 2016 10:34
-
-
Save teddyking/1e5b8942d916868b1e358830afc5cdc6 to your computer and use it in GitHub Desktop.
Example of Go sync.WaitGroup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"sync" | |
"time" | |
) | |
func main() { | |
var myWaitGroup sync.WaitGroup | |
myWaitGroup.Add(2) // Must wait for 2 calls to 'done' before moving on | |
go func(w *sync.WaitGroup) { | |
fmt.Println("Start gorouting 1") | |
fmt.Println("End gorouting 1") | |
w.Done() | |
}(&myWaitGroup) | |
go func(w *sync.WaitGroup) { | |
fmt.Println("Start gorouting 2") | |
time.Sleep(time.Second * 3) | |
fmt.Println("End gorouting 2") | |
w.Done() | |
}(&myWaitGroup) | |
fmt.Println("Waiting for all goroutines to exit") | |
myWaitGroup.Wait() | |
fmt.Println("Waited for all goroutines to exit") | |
} |
defer wg.Wait()
is more resilient :)
👍 @prozz
defer wg.Wait()
is more resilient :)
defer is have overhead (50-100ns)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@FelixSeptem you mean that the
WaitGroup
var is implicitly passed into the anonymous function as a pointer variable?If so, indeed you could turn it into