25. Go - Wait Sync
Wait provides a method to prevent application from closing prematurely while using goroutines.
var wg sync.WaitGroup // creates a sync waitgroup
wg.Add() // add how many waitgroups there are. takes in an int
defer wg.Done() // finishes a waitgroup. it is deferred so will be called when function finishes.
wg.Done() // also works by itself without defer
wg.Wait() // a method that waits for the waitgroups to finish.
Example:
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func main() {
wg.Add(2)
go count()
go count()
wg.Wait()
}
func count() {
defer wg.Done()
for i := 0; i < 10; i++ {
fmt.Println(i)
}
}
Comments
Post a Comment