Getting to Know Sync Once On Golang
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.
1var count = 0
2
3func OnlyOnce() {
4 count++
5}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.
1func main() {
2 var once sync.Once
3 var wg sync.WaitGroup
4
5 for i := 0; i < 100; i++ {
6 go func() {
7 wg.Add(1)
8 once.Do(OnlyOnce)
9 wg.Done()
10 }()
11 }
12 wg.Wait()
13 fmt.Println(count)
14}11Conclusion
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.