Go — Goroutines Basics
📌 Covered in this chapter:
go keyword · M:N scheduler model · Green threads (~2KB stack) · sync.WaitGroup · Preventing main exit
Welcome to Go — Goroutines Basics in our Go Complete Masterclass! Launch thousands of concurrent lightweight green threads using the go keyword and sync.WaitGroup synchronization.
1Goroutines & Go Concurrency Architecture
Goroutine ante Go runtime manage chese highly lightweight, concurrent thread of execution. OS threads ki constraint unna space lo, single OS thread multi-goroutines ni execute cheyyagaladhu.
Go M:N Scheduler Architecture:
[ OS Thread M1 ] [ OS Thread M2 ]
│ │
[ Go Scheduler ] [ Go Scheduler ]
├── Goroutine 1 (2KB) ├── Goroutine 3 (2KB)
└── Goroutine 2 (2KB) └── Goroutine 4 (2KB)
Go — Goroutines & sync.WaitGroup
▶ Run Code
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done() // Signal completion
fmt.Printf("Worker %d starting...\n", id)
time.Sleep(500 * time.Millisecond)
fmt.Printf("Worker %d finished!\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(i, &wg) // Launch concurrent goroutine
}
wg.Wait() // Wait for all goroutines to finish
fmt.Println("All workers completed successfully!")
}
💻 Live Go Code Execution
Test and run this Go program in our online high-performance Go compiler environment:
Open in Online Go Compiler →