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.
- You start the pasta (Takes 10 mins).
- You wait.
- You start the sauce (Takes 5 mins).
- You wait.
- 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
- You say:
gocookPasta() - You immediately say:
gocookSauce() - Both chefs work at the same time.
- 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
- go keyword: The magic word that starts a background task.
- Lightweight: Goroutines use almost no memory.
- 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)! :::