Go Concurrency
Understanding concurrent programming in Go
🚀 What is Go Concurrency?
Go concurrency allows multiple functions to run simultaneously, making programs faster and more efficient. Go uses goroutines and channels to handle concurrent operations safely and elegantly.
// Simple concurrent example
package main
import (
"fmt"
"time"
)
func main() {
go sayHello()
time.Sleep(1 * time.Second)
}
func sayHello() {
fmt.Println("Hello from goroutine!")
}
Key Concurrency Concepts
Goroutines
Lightweight threads managed by Go runtime
go function()
Channels
Communication pipes between goroutines
ch := make(chan int)
Select Statement
Choose between multiple channel operations
select {
case <-ch1:
case <-ch2:
}
Mutex & Locks
Protect shared data from race conditions
var mu sync.Mutex
mu.Lock()
mu.Unlock()
🔹 Why Use Concurrency?
Concurrency helps your programs handle multiple tasks efficiently:
Benefits of Concurrency:
- Performance: Handle multiple operations simultaneously
- Responsiveness: Keep applications responsive during long operations
- Resource Utilization: Make better use of multi-core processors
- Scalability: Handle more users and requests
// Sequential vs Concurrent example
package main
import (
"fmt"
"time"
)
func main() {
// Sequential - takes 3 seconds
task1()
task2()
task3()
// Concurrent - takes 1 second
go task1()
go task2()
go task3()
time.Sleep(2 * time.Second)
}
func task1() { time.Sleep(1 * time.Second); fmt.Println("Task 1") }
func task2() { time.Sleep(1 * time.Second); fmt.Println("Task 2") }
func task3() { time.Sleep(1 * time.Second); fmt.Println("Task 3") }
🔹 Basic Concurrent Program
Here's a simple example showing concurrent execution:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
// Start 3 goroutines
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(i, &wg)
}
// Wait for all goroutines to finish
wg.Wait()
fmt.Println("All workers completed!")
}
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("Worker %d finished\n", id)
}
Output:
Worker 1 starting Worker 2 starting Worker 3 starting Worker 1 finished Worker 2 finished Worker 3 finished All workers completed!