go / beginner
Snippet
Introduction to Goroutines for Concurrency
Goroutines are lightweight threads managed by the Go runtime, enabling concurrent execution. Simply prefix a function call with 'go' to run it concurrently. Unlike parallel processing (using multiple CPU cores), concurrent processing through goroutines allows a single CPU to handle multiple tasks by switching between them. The scheduler handles switching automatically.
snippet.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
package mainimport ("fmt""time")func main() {fmt.Println("Start of program")go say("Hello", 3)go say("Go", 3)time.Sleep(time.Second * 2)fmt.Println("End of program")}func say(word string, count int) {for i := 0; i < count; i++ {fmt.Println(word)time.Sleep(time.Millisecond * 100)}}
Breakdown
1
go say("Hello", 3)
The 'go' keyword launches the function as a goroutine - runs independently and concurrently
2
time.Sleep(time.Second * 2)
Sleep pauses execution for the specified duration, allowing goroutines to complete
3
go func() { }()
Anonymous goroutine - useful for quick concurrent operations without defining a function
4
fmt.Println(word)
Each goroutine prints independently, output order may vary due to scheduling