Example 1
Take an example below:
import "fmt"
funcrt() {
fmt.Println("First Go routine")
}
funcrt2() {
fmt.Println("Second go routine")
}
funcmain() {
go rt()
go rt2()
}
If you run the code above, the program prints nothing. This is because the main function is terminated upon launching the goroutines. Since the main function is the entry point of a Go program, once it ends, the program ends.
To handle such a case, we can use Golang Waitgroup. The Waitgroup method has three main methods:
- Add() – the Waitgroup acts as a counter holding the number of functions or go routines to wait for. If the counter becomes 0, the Waitgroup releases the goroutines. We use the Add method to add a specific value to the Waitgroup counter.
- Wait() – The wait method blocks the execution until Waitgroup counter becomes 0.
- Done() – decreases the Waitgroup counter by a value of 1
Let us now recreate the previous example and use Waitgroup to pause the execution.
import (
"fmt"
"sync"
)
funcrt(wg *sync.WaitGroup) {
fmt.Println("First Go routine")
deferwg.Done() // remove goroutine from waitgroup counter
}
funcrt2(wg *sync.WaitGroup) {
fmt.Println("Second go routine")
deferwg.Done()
}
funcmain() {
// new waitgroup
wg := new(sync.WaitGroup)
// add two go routines
wg.Add(2)
go rt(wg)
go rt2(wg)
// block execution until done
wg.Wait()
}
Now, if we run the code again, we should see an output as:
Second go routine
First Go routine
Example 2
You can also use Waitgroups with anonymous functions. An example is as shown below:
import (
"fmt"
"sync"
)
wg.Done()
// }
funcmain() {
varwgsync.WaitGroup
fori := 1; i<= 5; i++ {
wg.Add(1)
i := i
gofunc() {
deferwg.Done()
fmt.Printf("Starting routine: %d\n", i)
}()
}
wg.Wait()
}
The example above illustrates how to use Waitgroups with an anonymous function. The code above should return:
Starting routine: 3
Starting routine: 4
Starting routine: 5
Starting routine: 2
Conclusion
In this article, we covered the basics of working with the Waitgroup subpackage from the sync package in Go. Waitgroups allows you to pause the execution until a group of functions or goroutines finish executing.