Concurrency is a fundamental concept in modern software development, especially when building scalable and efficient applications. In Go, concurrency is built into the language from the ground up, making it easy to write programs that can handle multiple tasks simultaneously. This tutorial will introduce you to the basics of concurrency in Go, focusing on goroutines and channels.
Concurrency in Go is primarily achieved through two mechanisms: goroutines and channels.
Let's start with an example that demonstrates how to use goroutines in Go.
1package main23import (4"fmt"5"time"6)78func sayHello() {9for i := 0; i < 5; i++ {10fmt.Println("Hello from goroutine")11time.Sleep(1 * time.Second)12}13}1415func main() {16go sayHello()17fmt.Println("Hello from main function")1819// Wait for the goroutine to finish20time.Sleep(6 * time.Second)21}
In this example, we define a sayHello function that prints "Hello from goroutine" five times with a one-second delay between each print. We then start a goroutine by calling go sayHello() in the main function. The main function also prints "Hello from main function".
To ensure that the program waits for the goroutine to finish before exiting, we use time.Sleep(6 * time.Second) at the end of the main function. This is a simple way to synchronize the execution, but in real-world applications, you would typically use channels or other synchronization primitives.
Channels are used to communicate between goroutines and synchronize their execution. Let's see how channels work with an example.
1package main23import (4"fmt"5)67func worker(id int, ch chan int) {8for n := range ch {9fmt.Printf("Worker %d received %d10", id, n)11}12}1314func main() {15ch := make(chan int)1617// Start three workers18for i := 1; i <= 3; i++ {19go worker(i, ch)20}2122// Send numbers to the channel23for i := 0; i < 5; i++ {24ch <- i25}2627close(ch) // Close the channel when done sending2829// Wait for all workers to finish30time.Sleep(1 * time.Second)31}
In this example, we define a worker function that receives integers from a channel and prints them. In the main function, we create a channel of type int using make(chan int). We then start three worker goroutines, each receiving messages from the same channel.
We send five numbers to the channel using ch <- i, and after sending all numbers, we close the channel using close(ch). This signals to the workers that no more messages will be sent. Finally, we use time.Sleep(1 * time.Second) to wait for the workers to finish processing the messages.
In this tutorial, you learned about the basics of concurrency in Go, including goroutines and channels. In the next section, we will dive deeper into goroutines, exploring how they are scheduled, managed, and used in more complex scenarios.
Stay tuned for more advanced topics on Go concurrency!