Skip to content

Instantly share code, notes, and snippets.

@teddyking
Created August 23, 2016 10:34
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save teddyking/1e5b8942d916868b1e358830afc5cdc6 to your computer and use it in GitHub Desktop.
Save teddyking/1e5b8942d916868b1e358830afc5cdc6 to your computer and use it in GitHub Desktop.
Example of Go sync.WaitGroup
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")
}
@FelixSeptem
Copy link

unnecessary to pass WaitGroup to goroutine, closure works fine.

@chrisvdg
Copy link

@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

func main() {
	var myWaitGroup sync.WaitGroup

	myWaitGroup.Add(2)

	go func() {
		fmt.Println("Start gorouting 1")
		fmt.Println("End gorouting 1")
		myWaitGroup.Done()
	}()

	go func() {
		fmt.Println("Start gorouting 2")
		time.Sleep(time.Second * 3)
		fmt.Println("End gorouting 2")
		myWaitGroup.Done()
	}()

	fmt.Println("Waiting for all goroutines to exit")
	myWaitGroup.Wait()
	fmt.Println("Waited for all goroutines to exit")
}

@prozz
Copy link

prozz commented Nov 20, 2018

defer wg.Wait() is more resilient :)

@alexellis
Copy link

👍 @prozz

@idcooldi
Copy link

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