Goroutines are lightweight threads managed by the Go programming language runtime that allow functions to run concurrently. They are more efficient than traditional OS threads because they require less memory and have faster startup time.
Every Go program starts with a main goroutine, and when it finishes execution, all other goroutines are terminated.
- Managed by Go runtime (not OS directly)
- Enable easy concurrency using the go keyword
- Multiple goroutines can run simultaneously
Syntax
func functionName() {
// statements
}
// Run as Goroutine
go functionName()
Example: Demonstrates basic Goroutine execution where a function runs concurrently with the main function, but may not complete before the program exits.
package main
import "fmt"
func display(str string) {
for i := 0; i < 3; i++ {
fmt.Println(str)
}
}
func main() {
go display("Hello, Goroutine!")// Runs concurrently
display("Hello, Main!")
}
Output
Hello, Main! Hello, Main! Hello, Main!
Explanation:
- go display(...) runs in a separate goroutine
- display("Hello, Main!") runs in the main goroutine
- The program may exit before the goroutine finishes
Running Goroutines with Delay
To allow goroutines to complete, we can use time.Sleep(). Example:
package main
import (
"fmt"
"time"
)
func display(str string) {
for i := 0; i < 3; i++ {
fmt.Println(str)
}
}
func main() {
go display("Hello, Goroutine!")
time.Sleep(time.Second)// Wait for goroutine
display("Hello, Main!")
}
Output:
Hello, Goroutine!
Hello, Goroutine!
Hello, Goroutine!
Hello, Main!
Hello, Main!
Hello, Main!
Explanation:
- time.Sleep() pauses the main goroutine
- This gives time for other goroutines to execute
Anonymous Goroutines
Anonymous functions can also run as Goroutines by using the 'go' keyword.
Syntax
go func(parameters) {
// function logic
}(arguments)
Example: Shows an anonymous Goroutine with a delay using time.Sleep() to ensure it completes execution before the main function ends.
package main
import (
"fmt"
"time"
)
func main() {
go func(s string) {
for i := 0; i < 3; i++ {
fmt.Println(s)
time.Sleep(500 * time.Millisecond)
}
}("Hello from Anonymous Goroutine!")
time.Sleep(2 * time.Second) // Allow Goroutine to finish
fmt.Println("Main function complete.")
}
Output
Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Hello from Anonymous Goroutine! Main function complete.
Advantages vs Disadvantages
| Advantages | Disadvantages |
|---|---|
| Lightweight and fast | Hard to control execution order |
Easy to use (go keyword) | Requires synchronization |
| Efficient concurrency model | Debugging can be tricky |