Goroutine Basics
What is a Goroutine?
In Go, a goroutine is a lightweight thread managed by the Go runtime. Unlike traditional threads, goroutines are incredibly cheap and can be created with minimal overhead. They allow developers to write concurrent programs easily and efficiently.
Creating Goroutines
Goroutines are created using the go
keyword followed by a function call. Here's a simple example:
package main
import (
"fmt"
"time"
)
func printMessage(message string) {
fmt.Println(message)
}
func main() {
// Create a goroutine
go printMessage("Hello from goroutine")
// Main function continues immediately
fmt.Println("Main function")
// Add a small delay to allow goroutine to execute
time.Sleep(time.Second)
}
Goroutine Characteristics
Characteristic |
Description |
Lightweight |
Minimal memory overhead |
Managed by Go Runtime |
Scheduled and multiplexed efficiently |
Communication |
Use channels for safe communication |
Scalability |
Can create thousands of goroutines |
Concurrency vs Parallelism
graph TD
A[Concurrency] --> B[Multiple tasks in progress]
A --> C[Not necessarily simultaneous]
D[Parallelism] --> E[Multiple tasks executing simultaneously]
D --> F[Requires multiple CPU cores]
Anonymous Goroutines
You can also create goroutines with anonymous functions:
package main
import (
"fmt"
"time"
)
func main() {
go func() {
fmt.Println("Anonymous goroutine")
}()
time.Sleep(time.Second)
}
Key Points to Remember
- Goroutines are not OS threads
- They are managed by Go's runtime scheduler
- Creating a goroutine is very cheap
- Use channels for synchronization and communication
Goroutines are designed to be lightweight and efficient. The Go runtime can manage thousands of goroutines with minimal overhead, making concurrent programming in Go both simple and performant.
At LabEx, we recommend understanding goroutine basics as a fundamental skill for Go developers looking to build scalable and concurrent applications.