Learn how to execute code in parallel using Goroutines and Channels in Go.
A **Goroutine** is a lightweight concurrent execution thread in Go. Unlike traditional threads, Goroutines are **fast and memory-efficient**.
go myFunction()
💡 Adding `go` before a function call launches **a new Goroutine**, which runs in parallel.
Feature | Goroutines (Go) | Threads (Java, C++) |
---|---|---|
Creation | Very fast and lightweight | Heavy, consumes more memory |
Management | Handled by the Go runtime | Managed by the operating system |
Maximum number | Can execute thousands | Limited by system resources |
Goroutines can communicate with each other using **Channels**, which allow synchronized data exchange.
ch := make(chan int) // Creating a channel
💡 A channel works like a pipeline: one Goroutine sends data, another receives it.
goroutines.go
.package main
import (
"fmt"
"time"
)
func displayMessage(msg string, ch chan string) {
time.Sleep(2 * time.Second)
ch <- msg // Sending the message to the channel
}
func main() {
ch := make(chan string)
go displayMessage("Goroutine 1 finished", ch)
go displayMessage("Goroutine 2 finished", ch)
fmt.Println(<-ch) // Retrieves the first response
fmt.Println(<-ch) // Retrieves the second response
}
Goroutine 1 finished
Goroutine 2 finished
📚 Learn more about Goroutines in Go:
Official Go Documentation🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊