Want to learn how to build better Go applications faster and easier? You can.
Check out my course on the Go Standard Library. You can check it out now for free.
Go routines are one of the most powerful and exciting features of the Go programming language. In this article, we will explore what go routines are, how they work, why they matter, and provide a step-by-step demonstration to help you get started.
Go routines are lightweight threads that can be used to execute functions concurrently. They allow your program to perform multiple tasks at the same time, improving performance and responsiveness. Go routines are scheduled by the Go runtime, which manages the creation, execution, and termination of go routines.
A go routine is started using the go
keyword followed by a function call. The function called in a go routine will run concurrently with other goroutines and the main program.
package main
import "fmt"
func sayHello(name string) {
for i := 0; i < 5; i++ {
fmt.Println("Hello, ", name)
}
}
func main() {
go sayHello("John")
sayHello("Jane")
}
In this example, the sayHello
function is called twice, once in a go routine and once directly. Both calls will run concurrently.
Go routines are important because they allow you to write concurrent programs that can take advantage of multi-core processors. This can lead to significant performance improvements for CPU-bound tasks.
To demonstrate the power of go routines, let’s create a simple program that calculates the sum of squares for two lists of numbers. We’ll calculate the sums in separate goroutines and print the results.
package main
import "fmt"
import "time"
func sumSquares(numbers []int) int {
var sum int
for _, num := range numbers {
sum += num * num
}
return sum
}
func main() {
numbers1 := []int{1, 2, 3, 4, 5}
numbers2 := []int{6, 7, 8, 9, 10}
go func() {
result1 := sumSquares(numbers1)
fmt.Println("Sum of squares for numbers1:", result1)
}()
go func() {
result2 := sumSquares(numbers2)
fmt.Println("Sum of squares for numbers2:", result2)
}()
time.Sleep(time.Second) // let the goroutines run
}
This program starts two go routines to calculate the sum of squares for two lists of numbers. The results are printed after a short delay.
When working with go routines, follow these best practices:
Go routines are an essential feature of the Go programming language that allows you to write concurrent programs with ease. By understanding how go routines work, why they matter, and following best practices, you can write efficient, responsive, and scalable programs that take advantage of modern computers' hardware capabilities.