Introduction
Waitgroup is a feature of Golang that is used to wait for a process carried out by several goroutines. This is done because we need to do the process simultaneously but when we continue the next process we need data from the previous result so we have to wait first from the previous process to get the data.
For example, we want to run several processes using * goroutine*, but we want all processes to finish first before the application is finished, then this case we can use Waitgroup
. In this case we will mark the processes that are running using goroutine usually with Add(int)
command. Once the process is complete then we will call the Done()
method and to wait for all processes to complete we can use Wait()
.
Implementation of sync.WaitGroup
We will try to simulate how to use this WaitGroup
in the goal code, in this case we will use a goroutine that is run simultaneously using a loop 100 times. For more details, see the code below.
func HelloWorld(wg *sync.WaitGroup) {
defer wg.Done()
wg.Add(1)
fmt.Println("Hello")
time.Sleep(1 * time.Second)
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
go HelloWorld(&wg)
}
wg.Wait()
fmt.Println("Finish")
}
From the code above, if we run it, it will print Hello
100 times but the process is so fast, because we use * goroutine* even though the process of the function of HelloWorld
has 1 second to process. This proves that the use of WaitGroup
will wait for which process takes the longest by calling the Wait()
function then if all have finished the program will end.
The result of the program when it is run
Hello
Hello
...
...
Hello
Hello
Finish
Conclusion
The use of WaitGroup
is usually used for processes that want to run simultaneously using goroutine but all of these processes we want to wait for the results to be completed, because the process is the result of the data needed for the next process. Make sure the running WaitGroup
is closed with the wg.Done()
function so that the process does not continue to wait resulting in
Deadlock and how to overcome it in our program.