Skip to content

Module 1: Goroutines (The Gopher Army)

📚 Module 1: Goroutines

Course ID: GO-109
Subject: The Gopher Army

In other languages, starting a “Thread” is a big deal. It takes a lot of memory and time. In Go, we have Goroutines. They are incredibly lightweight threads that allow you to do thousands of things at once.


🏗️ Step 1: The “Sequential” Problem

Imagine you are a Chef.

  1. You start the pasta (Takes 10 mins).
  2. You wait.
  3. You start the sauce (Takes 5 mins).
  4. You wait.
  5. Total time: 15 minutes.

🏗️ Step 2: The Goroutine Solution

In Go, you just add the word go before a function call. It’s like hiring a second chef instantly.

🧩 The Analogy: Hiring Help

  1. You say: go cookPasta()
  2. You immediately say: go cookSauce()
  3. Both chefs work at the same time.
  4. Total time: 10 minutes.

In Code:

func main() {
    go longTask("Task 1") // Starts in the background
    go longTask("Task 2") // Starts in the background
    
    // Main doesn't wait! It finishes immediately.
}

🏗️ Step 3: Why are they so fast?

A standard Operating System thread takes about 1MB of memory. A Goroutine only takes about 2KB.

  • You can’t start 10,000 threads on a laptop (it will crash).
  • You CAN start 100,000 Goroutines on a laptop without even breaking a sweat.

🥅 Module 1 Review

  1. go keyword: The magic word that starts a background task.
  2. Lightweight: Goroutines use almost no memory.
  3. Non-blocking: The main program keeps moving while background tasks run.

:::tip Slow Learner Note The main problem with Goroutines is that the main() function might finish before the background tasks are done. We solve this using Channels (Module 2)! :::