How to coordinate and synchronize Goroutines using sync.Once in Golang?

In Go, the sync.Once package provides a mechanism to coordinate and synchronize Goroutines to ensure that a particular operation is executed only once, even if multiple Goroutines are calling it concurrently. Here's how you can use sync.Once to achieve this:

  1. Import the sync package:
import ( "sync" )
  1. Define a function that you want to execute only once:
func initialize() { fmt.Println("Initialized.") }
  1. Create an instance of sync.Once:
var once sync.Once
  1. In each Goroutine, call the Do method of sync.Once passing the function you want to execute:
func main() { wg := sync.WaitGroup{} for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() once.Do(initialize) }() } wg.Wait() }

In the example above, we have created 10 Goroutines that call the initialize function. However, due to the sync.Once package, the initialize function is executed only once, regardless of how many Goroutines call it. The output will be:

Initialized.

Note that the sync.Once package ensures that the function is executed only once, even if there is an error during the execution. Once a Goroutine calls Do, the other Goroutines will wait until the first call is complete, and then all subsequent calls to Do will be ignored.

By using sync.Once, you can effectively coordinate and synchronize Goroutines to ensure that a particular operation is performed only once, eliminating any potential race conditions or concurrency issues.