How to use WaitGroup to delay execution of the main function in Go by example?
Use WaitGroup to delay execution of the main function until after all goroutines are completes
In Go, you can use a WaitGroup to delay the execution of the main function until after all goroutines have completed. A WaitGroup is a synchronization primitive that allows you to block the execution of a goroutine until a set of related goroutines have completed.
Example
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go func(i int) {
fmt.Printf("Starting goroutine %d\n", i)
time.Sleep(2 * time.Second)
fmt.Printf("Ending goroutine %d\n", i)
wg.Done()
}(i)
}
wg.Wait()
fmt.Println("All goroutines have completed")
}
Output
Starting goroutine 3
Starting goroutine 2
Starting goroutine 1
Ending goroutine 3
Ending goroutine 1
Ending goroutine 2
All goroutines have completed
Explaination:
we create a WaitGroup
called wg
to synchronize the goroutines. We then create three goroutines using a for loop and increment the wait group counter using wg.Add(1)
before each goroutine is launched.
Inside each goroutine, we print a message to the console indicating that the goroutine has started, simulate some work using time.Sleep()
, and then print another message indicating that the goroutine has completed. Finally, we call wg.Done()
to decrement the wait group counter.
After all goroutines have been launched, we call wg.Wait()
to block the execution of the main function until all goroutines have completed. Once all goroutines have completed, we print a message to the console indicating that all goroutines have completed.
Previous Article
Golang Tutorials
- Hello World
- Operators in Go
- Declarations in Go
- Values in Go
- Variables in Go
- For in Go
- If/Else in Go
- Switch in Go
- Arrays in Go
- Slices in Go
- Maps in Go
- Range in Go
- Functions in Go
- Closures in Go
- Recursion in Go
- Pointers in Go
- Strings and Runes in Go
- Structs in Go
- Methods in Go
- Interfaces in Go
- Generics in Go
- Errors in Go
- Goroutines in Go
- Channels in Go
- Select in Go
- Timeouts in Go
- Timers in Go
- Worker Pools in Go
- WaitGroups in Go
- Mutexes in Go
- Sorting in Go
- Panic in Go
- Defer in Go
- Recover in Go
- JSON in Go
- XML in Go
- Time in Go
- Epoch in Go
- Time Formatting in Go
- Random Numbers in Go
- Number Parsing in Go
- URL Parsing in Go
- SHA256 Hashes in Go
- Base64 Encoding in Go
- Reading Files in Go
- Writing Files in Go
- File Paths in Go
- Directories in Go
- Testing and Benchmarking in Go
- Command-Line Arguments in Go
- Command-Line Flags in Go
- Command-Line Subcommands in Go
- Environment Variables in Go
- HTTP Client in Go
- HTTP Server in Go
- Context in Go
- Signals in Go