Skip to content

Instantly share code, notes, and snippets.

@zianwar
Last active February 3, 2020 18:46
Show Gist options
  • Save zianwar/71ce4c29537acd1a0632da8a33f7fd2d to your computer and use it in GitHub Desktop.
Save zianwar/71ce4c29537acd1a0632da8a33f7fd2d to your computer and use it in GitHub Desktop.
Execute Go Goroutines in Order
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func first(wait <-chan struct{}) {
defer wg.Done()
<-wait
fmt.Println("first")
}
func second(wait <-chan struct{}) {
defer wg.Done()
<-wait
fmt.Println("second")
}
func third(wait <-chan struct{}) {
defer wg.Done()
<-wait
fmt.Println("third")
}
func main() {
wg = sync.WaitGroup{}
wg.Add(3)
wait1 := make(chan struct{})
wait2 := make(chan struct{})
wait3 := make(chan struct{})
go third(wait3)
go first(wait1)
go second(wait2)
wait1 <- struct{}{}
wait2 <- struct{}{}
wait3 <- struct{}{}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment