Junior — Middle
Could you explain what it means to run and manage goroutines in Go?
sobes.tech AI
Answer from AI
In the Go language, goroutines are lightweight threads managed by the Go runtime. Starting a goroutine allows a function or method to run concurrently with the main thread without blocking it.
To start a goroutine, the keyword go is used before the function call:
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello() // start goroutine
// main thread continues to work
time.Sleep(time.Second) // to give the goroutine time to execute
}
Managing goroutines involves synchronization and coordination of their work. Channels (chan) are often used for this purpose, allowing safe and efficient data transfer between goroutines.
Example of using a channel to wait for a goroutine to finish:
func worker(done chan bool) {
fmt.Println("Goroutine work")
done <- true // signal completion
}
func main() {
done := make(chan bool)
go worker(done)
<-done // wait for signal
fmt.Println("Goroutine finished")
}
Thus, starting and managing goroutines is a way to organize concurrent code execution using lightweight threads and synchronization mechanisms.