capypad
0 day streak
go / beginner
Snippet

Goroutines: Lightweight Concurrency

Goroutines are lightweight threads managed by the Go runtime, started with the go keyword. They run concurrently (not necessarily parallel) with other code. The main function itself is a goroutine, and the program exits when the main goroutine ends, even if other goroutines are still running. Use time.Sleep or sync.WaitGroup to wait for goroutines to complete. Goroutines are cheap - you can have thousands running simultaneously.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package main
 
import (
"fmt"
"time"
)
 
func greet(name string) {
fmt.Printf("Hello, %s!\n", name)
}
 
func task(id int) {
for i := 1; i <= 3; i++ {
fmt.Printf("Task %d: step %d\n", id, i)
time.Sleep(100 * time.Millisecond)
}
}
 
func main() {
// Launch goroutine - runs concurrently
go greet("Alice")
go greet("Bob")
 
// Launch multiple concurrent tasks
for i := 1; i <= 3; i++ {
go task(i)
}
 
// Wait long enough for goroutines to complete
time.Sleep(400 * time.Millisecond)
fmt.Println("Main function done")
}
Breakdown
1
go greet("Alice")
Starts a new goroutine - greet runs concurrently with main
2
time.Sleep(400 * time.Millisecond)
Main waits long enough for other goroutines to finish
3
fmt.Println("Main function done")
May print before all goroutines finish - execution order is not guaranteed