Concurrency with Goroutines
Concurrency in Go is achieved using goroutines and channels. Goroutines are lightweight threads managed by the Go runtime, making it easy to run multiple functions concurrently. Here’s a example:
Example: Running Multiple Functions Concurrently
package main
import (
"fmt"
"time"
)
func sayHello() {
for i := 0; i < 5; i++ {
fmt.Println("Hello")
time.Sleep(100 * time.Millisecond)
}
}
func sayWorld() {
for i := 0; i < 5; i++ {
fmt.Println("World")
time.Sleep(100 * time.Millisecond)
}
}
func main() {
go sayHello()
go sayWorld()
time.Sleep(1 * time.Second)
}
Explanation
Goroutines: Use the
go
keyword to runsayHello
andsayWorld
functions concurrently.Sleep: Use
time.Sleep
to keep the main function running long enough for goroutines to complete.
By utilizing goroutines, you can efficiently run multiple tasks concurrently in Go.