Concurrency is an essential feature of modern computing, and the Go programming language is designed to make it easy to write concurrent programs. Go routines are one of the main ways of achieving concurrency in Go. In this article, we will explore what Go routines are and how to use them.
What are Go routines?
In Go, a routine is a lightweight thread of execution that can be used to perform a task concurrently with other routines. Go routines are similar to threads in other languages, but they are cheaper in terms of memory usage and overhead. This makes it possible to create a large number of routines without worrying about performance.
How to create a Go routine?
In Go, you can create a routine using the go keyword followed by a function call. Here is an example:
func main() {
go sayHello()
fmt.Println("main function")
}
func sayHello() {
fmt.Println("Hello")
}
In this example, we have created a routine that calls the sayHello
function concurrently with the main
function. When you run this program, you will see the following output:
main function Hello
As you can see, the main
function continues to execute even though the sayHello
routine is still running.
Passing arguments to a Go routine
You can pass arguments to a Go routine by including them in the function call. Here is an example:
func main() {
go printNumbers(1, 2, 3, 4, 5)
fmt.Println("main function")
}
func printNumbers(numbers ...int) {
for _, number := range numbers {
fmt.Println(number)
}
}
In this example, we have created a routine that calls the printNumbers
function with a list of integers. The printNumbers
function uses the range
keyword to iterate over the list of integers and print each one.
main function Hello
Waiting for a Go routine to finish
Sometimes, you may need to wait for a Go routine to finish before continuing with your program. You can use channels to achieve this. Here is an example:
func main() {
c := make(chan string)
go printMessage("Hello", c)
message := <-c fmt.Println(message)
}
func printMessage(message string, c chan string) {
time.Sleep(time.Second) c <- message
}
In this example, we have created a channel called c
and passed it to the printMessage
function. The printMessage
function waits for one second using the time.Sleep
function and then sends the message
to the channel. The main
function waits for a message from the channel using the <-
operator and then prints it.
Conclusion
Go routines are a powerful feature of the Go programming language that makes it easy to write concurrent programs. By using Go routines, you can take advantage of the multiple cores in modern CPUs and make your programs more efficient. With the examples above, you should be able to get started with Go routines and explore the full potential of Go's concurrency features.
Comments