[Golang (Go)] Use sync.Once to execute only the first call

sync.Once

Once is an object that will perform exactly one action.

.Do calls the function f if and only if .Do is being called for the first time for this instance of Once. In other words, given var once Once if once.Do(f) is called multiple times, only the first call will invoke f,
even if f has a different value in each invocation.

A new instance of Once is required for each function to execute.

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// main.go

package main

import (
"fmt"
"sync"
)

func main() {
var once sync.Once
onceBody := func() {
fmt.Println("Only once")
}
done := make(chan bool)
for i := 0; i < 10; i++ {
go func() {
once.Do(onceBody) // Execute only the first call
done <- true
}()
}
for i := 0; i < 10; i++ {
<-done
}
}
1
2
$ go run main.go
Only once

References

[1] Once | sync - The Go Programming Language - https://golang.org/pkg/sync/#example_Once

[2] Run Code Once on First Load (Concurrency Safe) · GolangCode - https://golangcode.com/run-code-once-with-sync/

[3] src/sync/once.go - The Go Programming Language - https://golang.org/src/sync/once.go

[4] Using Synchronization Primitives in Go | by Abhishek Gupta | Better Programming - https://betterprogramming.pub/using-synchronization-primitives-in-go-mutex-waitgroup-once-2e50359cb0a7