Goroutine with sync.waitGroup output different value each time

Issue

Code below will print different values each time after execution, but I want the values to be same, how to change the code below without using time.Sleep

package main

import (
    "fmt"
    "sync"
)

var total int
var wg sync.WaitGroup

// Inc increments the counter for the given key.
func inc(num int) {
    total += num
    wg.Done()
}

// Value returns the current value of the counter for the given key.
func getValue() int {
    return total
}

func main() {
    for i := 1; i <= 1000; i++ {
        wg.Add(1)
        go inc(i)
    }
    wg.Wait()
    fmt.Println(getValue())
}

Solution

You have a data race, and the outcome is undefined. You have to synchronize the access to the share variable:

var total int
var lock sync.Mutex
var wg sync.WaitGroup

// Inc increments the counter for the given key.
func inc(num int) {
    lock.Lock()
    defer lock.Unlock()
    total += num
    wg.Done()
}

// Value returns the current value of the counter for the given key.
func getValue() int {
    lock.Lock()
    defer lock.Unlock()
    return total
}

Or, use sync/atomic to access/modify the variable.

Answered By – Burak Serdar

Answer Checked By – Cary Denson (GoLangFix Admin)

Leave a Reply

Your email address will not be published.