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 efficient 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 execution
fmt.Println("Main function")
// Add a small delay to allow goroutine to execute
time.Sleep(time.Second)
}
Goroutine Characteristics
Characteristic |
Description |
Lightweight |
Consumes minimal memory (around 2KB of stack) |
Scalable |
Can create thousands of goroutines simultaneously |
Managed by Runtime |
Go runtime handles scheduling and management |
Concurrent |
Multiple goroutines can run concurrently |
Concurrency vs Parallelism
graph TD
A[Concurrency] --> B[Multiple tasks in progress]
A --> C[Switching between tasks]
D[Parallelism] --> E[Multiple tasks running simultaneously]
D --> F[Multiple CPU cores]
Synchronization with WaitGroup
To wait for goroutines to complete, use sync.WaitGroup
:
package main
import (
"fmt"
"sync"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
// Simulate work
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 5; i++ {
wg.Add(1)
go worker(i, &wg)
}
wg.Wait()
fmt.Println("All workers completed")
}
Best Practices
- Use goroutines for I/O-bound or independent tasks
- Avoid creating too many goroutines
- Use channels for communication between goroutines
- Always handle potential race conditions
When to Use Goroutines
- Parallel processing
- Network programming
- Background tasks
- Handling multiple client connections
By understanding these basics, developers can leverage the power of concurrency in Go with LabEx's advanced programming techniques.