To perform one-time initialization of shared resources in Golang, you can use the sync.Once
package. The sync.Once
type provides a mechanism to ensure that a particular function is called only once, regardless of how many times it is called from different goroutines.
Here is an example of how to use sync.Once
to perform one-time initialization:
import (
"sync"
)
type SharedResources struct {
// Declare your shared resources here
}
func initializeResources() {
// Initialize your shared resources here
}
sync.Once
:var once sync.Once
sync.Once
:func initializeOnce(resources *SharedResources) {
once.Do(func() {
initializeResources()
})
}
initializeOnce
function to initialize the shared resources wherever it is needed:func main() {
resources := &SharedResources{}
initializeOnce(resources)
// Use the shared resources here
}
By using sync.Once
, the initializeResources
function will only be called once, regardless of how many times initializeOnce
is called from different goroutines. This ensures that your shared resources are properly initialized and ready to be used.