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")
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?