Learn how to optimize Goroutine management using Workers, Mutex, and WaitGroup.
Go makes concurrency easy with Goroutines, but poor management can lead to data conflicts or excessive resource consumption.
concurrency.go
.package main
import (
"fmt"
"sync"
"time"
)
const numWorkers = 3
const numTasks = 6
func worker(id int, tasks <-chan int, wg *sync.WaitGroup, mutex *sync.Mutex, result *int) {
defer wg.Done()
for task := range tasks {
fmt.Printf("Worker %d processing task %d\n", id, task)
time.Sleep(time.Second)
mutex.Lock()
*result += task // Protect concurrent access with Mutex
mutex.Unlock()
}
}
func main() {
tasks := make(chan int, numTasks)
var wg sync.WaitGroup
var mutex sync.Mutex
var result int
// Launch Workers
for i := 1; i <= numWorkers; i++ {
wg.Add(1)
go worker(i, tasks, &wg, &mutex, &result)
}
// Send tasks
for i := 1; i <= numTasks; i++ {
tasks <- i
}
close(tasks)
// Wait for all Goroutines to finish
wg.Wait()
fmt.Println("Sum of executed tasks:", result)
}
📚 Learn more about Go concurrency:
Read the Official Documentation Next Exercise →🚀 Enjoying these exercises? If you find them useful and want to support my work, buying me a coffee would be greatly appreciated! ☕😊