Add wait groups
This commit is contained in:
parent
9430f69b87
commit
fd31a65843
6
main.go
6
main.go
@ -12,7 +12,8 @@ package main
|
||||
// import "git.sangeeth.dev/gobyexample/closingchannels"
|
||||
// import "git.sangeeth.dev/gobyexample/timers"
|
||||
// import "git.sangeeth.dev/gobyexample/tickers"
|
||||
import "git.sangeeth.dev/gobyexample/workerpools"
|
||||
// import "git.sangeeth.dev/gobyexample/workerpools"
|
||||
import "git.sangeeth.dev/gobyexample/waitgroups"
|
||||
|
||||
func main() {
|
||||
// runes.Runes()
|
||||
@ -27,5 +28,6 @@ func main() {
|
||||
// closingchannels.ClosingChannels()
|
||||
// timers.Timers()
|
||||
// tickers.Tickers()
|
||||
workerpools.WorkerPools()
|
||||
// workerpools.WorkerPools()
|
||||
waitgroups.WaitGroups()
|
||||
}
|
||||
|
29
waitgroups/waitgroups.go
Normal file
29
waitgroups/waitgroups.go
Normal file
@ -0,0 +1,29 @@
|
||||
package waitgroups
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func worker(id int, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
fmt.Printf("worker #%d starting\n", id)
|
||||
time.Sleep(time.Duration((1 + rand.Intn(2))) * time.Second)
|
||||
fmt.Printf("worker #%d exiting\n", id)
|
||||
}
|
||||
|
||||
func WaitGroups() {
|
||||
numJobs := 3
|
||||
wg := sync.WaitGroup{}
|
||||
|
||||
for i := range numJobs {
|
||||
wg.Add(1)
|
||||
go worker(i, &wg)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
fmt.Println("Program exiting")
|
||||
}
|
Loading…
Reference in New Issue
Block a user