Exercise 4: Goroutines and Concurrency in Go

Learn how to execute code in parallel using Goroutines and Channels in Go.

What is a Goroutine?

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.

Difference Between Goroutines and Threads

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

Synchronization with Channels

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.

Exercise Instructions

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
}

Expected Output

Goroutine 1 finished
Goroutine 2 finished

Best Practices with Goroutines

📚 Learn more about Goroutines in Go:

Official Go Documentation
← Previous Exercise Next Exercise →

🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊


☕ Buy me a coffee