Introduction of sync.Once
We can use this feature in Golang to ensure that a function is executed only once. Sometimes if we already have many goroutines that are accessing, then with sync.Once
we can make sure that only the goroutine that has the first access can execute the function. So if there are other goroutines that are running, they will not execute and ignore the function.
To be clearer and more able to understand it, let’s just try the sample program code below.
Implementation and sample sync.Once
The first time we create a function and global variable that we will update the value of the global variable as below.
var count = 0
func OnlyOnce() {
count++
}
After that, we will create the main program using sync.WaitGroup
to initialize a goroutine with a count of 100 and access the function we created above.
func main() {
var once sync.Once
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
go func() {
wg.Add(1)
once.Do(OnlyOnce)
wg.Done()
}()
}
wg.Wait()
fmt.Println(count)
}
So, how is the output of our program or code above? The result will output like this
1
In fact, the process to access the function is 100 times.
Conclusion
sync.Once
for us is usually used to fill data or variables that are only accessed once and the rest we can use the data for the needs of other processes that are bound together. This is to reduce the cost
of access to the function and a lighter response time.