Concurrency in Go with Goroutines and Channels ⚙️
One of Go’s standout features is its built-in support for concurrency using goroutines and channels.
Goroutines
Goroutines are lightweight threads managed by the Go runtime. They are spawned using the go
keyword.
package main
import (
"fmt"
"time"
)
func sayHello() {
fmt.Println("Hello from goroutine")
}
func main() {
go sayHello()
time.Sleep(1 * time.Second) // Wait for goroutine to finish
}
Channels
Channels facilitate communication between goroutines.
ch := make(chan string)
// Sender
go func() {
ch <- "Data from goroutine"
}()
// Receiver
message := <-ch
fmt.Println(message)
Practical Example: Concurrent Prime Checking
Efficiently check multiple numbers for primality by launching goroutines and collecting results via channels.
Concurrency enables high-performance applications, optimizing resource utilization and responsiveness.