Golang WaitGroups

Israel Josué Parra Rosales
3 min readAug 1, 2022

--

A “waitGroup” is an important thing at the time to work with goroutines because it will help us when we need to wait until all the goroutines are completed.

The “waitGroup” help us with the fork-join model used by the goroutines because the main thread waits until the process executed in the fork is joined to the main thread again.

The “waitGroup” has defined four methods that will help us to control the “life cycle”, add(), wait(), done(), and state(). Lets us describe each one:

  • add(int)
    Is used to indicate/add the total goroutines to the waitgroup. Adding goroutines the main thread will wait until all off them are completed by calling done().
  • wait()
    Is used to indicate in the code that the flow is waiting by the goroutines ends.
  • done()
    Is used to indicate that the goroutine logic is completed.
  • state()
    State returns pointers to the state and sema fields stored within wg.state*. — (Taken from the golang documentation)

How do all that methods interact with each other?

  • So, when we add a goroutine to the “waitGroup” we have to ensure to terminate it using the done(), in other words, we need to mark as a “Done()” the equal number of goroutines that we are indicating by “Add()” if we don't do that the code will panic with “fatal error: all goroutines are asleep — deadlock!”.
  • The code defined after calling the “Wait()” method will be executed until all the goroutines are done.
  • If the wait is not called, then all the goroutines in the “waitGroup” will be executed asynchronously in a separate process.

Now let us have an example to see the “waitGroup” in action.

In the following example we going to execute three goroutines. Then in the line 13 we add them to the “waitGroup”, to simulate a process we just add a time sleep that in this example is different for each one of the goroutines, I do that to show you that doesn’t matter the time that takes to be completed the goroutine the waitGroup will stop the flow until all goroutines are “Done”.

Output:

Cool! … we are done with the waitGroup usage. In the next articles we will review about mutex that will help us to synchronize logic between goroutines.

Next Step: How to implement Mutex

This article is related to the Golang concurrency tutorial that you can find in the following link:

https://medium.com/@josueparra2892/concurrency-in-go-bf93e23bebd4

--

--

Israel Josué Parra Rosales

I'm a software developer with more than 11 years of experience. The last 9 years I have been working with Go. I love to learn and share my knowledge.