Goroutines & Concurrency Basics
Concurrency is built directly into the core design of Go. Goroutines are lightweight threads managed by the Go runtime, rather than the host operating system.
1 Goroutines vs. OS Threads (The `go` Keyword)
While standard OS threads require megabytes of stack memory, a **Goroutine** starts with just a few kilobytes. To launch a function concurrently as a goroutine, simply prepend the statement with the **`go`** keyword: `go doWork()`. The scheduler multiplexes thousands of goroutines onto a small number of physical OS threads automatically.
2 Goroutines Code
Let's run a program that launches functions concurrently using goroutines:
Go — Goroutines
▶ Run Code
package main
import (
"fmt"
"time"
)
func showMessage(msg string) {
for i := 1; i <= 3; i++ {
fmt.Println(msg)
time.Sleep(100 * time.Millisecond) // Yield execution thread
}
}
func main() {
// Launch function concurrently as a Goroutine
go showMessage("Async Work Running!")
// Main thread execution
showMessage("Main thread running!")
// Wait slightly to let the async goroutine finish before main exits
time.Sleep(150 * time.Millisecond)
}
3 Code Challenge
Challenge: Write a program that launches two goroutines. Each goroutine should print a unique counting sequence (e.g. one prints numbers 1-5, and the other prints letters A-E), sleeping for 50 milliseconds between prints.