When we need to call a function only once in multiple goroutines, how to achieve that? Golang has provided a package named sync, which has defined a struct named Once can be used to achieve above goal. For example, if we want to increase a variable in multiple goroutines just one time, we can write code as below,
package main
import (
"fmt"
"sync"
)
func worker(wg *sync.WaitGroup, i *int, once *sync.Once) {
defer wg.Done()
once.Do(func() {
*i = *i + 1
})
}
func main() {
var once sync.Once
var j int
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go worker(&wg, &j, &once)
}
wg.Wait()
fmt.Println(j)
}
The code above generates output as below,
1