type Singleton struct{} var instance *Singleton var once sync.Once func getInstance() *Singleton { once.Do(func() { instance = &Singleton{} }) return instance }
var waitGroup sync.WaitGroup var once sync.Once func setup() { once.Do(func() { fmt.Println("Setting up resources...") waitGroup.Add(1) }) } func main() { for i := 0; i < 10; i++ { go setup() } waitGroup.Wait() fmt.Println("All resources are ready.") }In this example, the "setup" function is executed only once, even though it is called concurrently across multiple goroutines. The "sync.WaitGroup" ensures that the main goroutine waits for all the "setup" functions to complete before printing the final message. Both examples use the "sync" package library to synchronize access to shared resources in concurrent programming.