Add wait groups

This commit is contained in:
Sangeeth Sudheer 2024-04-29 07:47:21 +05:30
parent 9430f69b87
commit fd31a65843
Signed by: x
GPG Key ID: F6D06ECE734C57D1
2 changed files with 33 additions and 2 deletions

View File

@ -12,7 +12,8 @@ package main
// import "git.sangeeth.dev/gobyexample/closingchannels" // import "git.sangeeth.dev/gobyexample/closingchannels"
// import "git.sangeeth.dev/gobyexample/timers" // import "git.sangeeth.dev/gobyexample/timers"
// import "git.sangeeth.dev/gobyexample/tickers" // 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() { func main() {
// runes.Runes() // runes.Runes()
@ -27,5 +28,6 @@ func main() {
// closingchannels.ClosingChannels() // closingchannels.ClosingChannels()
// timers.Timers() // timers.Timers()
// tickers.Tickers() // tickers.Tickers()
workerpools.WorkerPools() // workerpools.WorkerPools()
waitgroups.WaitGroups()
} }

29
waitgroups/waitgroups.go Normal file
View 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")
}