Last active
February 3, 2020 18:46
-
-
Save zianwar/71ce4c29537acd1a0632da8a33f7fd2d to your computer and use it in GitHub Desktop.
Execute Go Goroutines in Order
This file contains hidden or 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" | |
) | |
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