How do I start a goroutine safely in Go?

In Go, starting a goroutine safely involves understanding the concurrency model and avoiding data races. A goroutine is a lightweight thread managed by the Go runtime. When starting a goroutine, it's essential to ensure that shared resources are accessed in a thread-safe manner. The `sync` package provides synchronization primitives like mutexes and WaitGroups that can help manage concurrent access to shared variables.

Here’s a basic example of how to start a goroutine safely using a WaitGroup to wait for the completion of the goroutines:

package main import ( "fmt" "sync" ) func main() { var wg sync.WaitGroup // Start a goroutine for i := 0; i < 5; i++ { wg.Add(1) // Increment the WaitGroup counter go func(i int) { defer wg.Done() // Decrement the counter when the goroutine completes fmt.Println("Goroutine", i) }(i) } wg.Wait() // Wait for all goroutines to finish fmt.Println("All goroutines finished") }

Go goroutine concurrency synchronization data race