Getting to Know WaitGroup on Golang
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.
1func HelloWorld(wg *sync.WaitGroup) {
2 defer wg.Done()
3 wg.Add(1)
4 fmt.Println("Hello")
5 time.Sleep(1 * time.Second)
6}
7
8func main() {
9 var wg sync.WaitGroup
10
11 for i := 0; i < 100; i++ {
12 go HelloWorld(&wg)
13 }
14
15 wg.Wait()
16 fmt.Println("Finish")
17}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
1Hello
2Hello
3...
4...
5Hello
6Hello
7FinishConclusion
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.