golang

Golang Waitgroup

Golang Waitgroup allows you to block a specific code block to allow a set of goroutines to complete execution. An example would be to block the main function until the goroutines are completed and then unblocks the group.

Example 1

Take an example below:

package main

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:

  1. 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.
  2. Wait() – The wait method blocks the execution until Waitgroup counter becomes 0.
  3. Done() – decreases the Waitgroup counter by a value of 1

Let us now recreate the previous example and use Waitgroup to pause the execution.

package main

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:

$ go run waitgroup.go
Second go routine
First Go routine

Example 2

You can also use Waitgroups with anonymous functions. An example is as shown below:

package main
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: 1

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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list