Problem: Bounded Worker Pool with Ordered or Collected Results
Task: Given a slice of integers nums := []int{1, 2, …, 20}, compute the square of each number concurrently using at most 3 worker goroutines. Collect all results into a slice and print the total sum. Ensure there are zero goroutine leaks or race conditions (go run -race).
Concepts Used
| Feature | Unbuffered Channel | Buffered Channel |
|---|---|---|
| Creation | Created using make(chan T) with a capacity of 0. | Created using make(chan T, N) with a capacity greater than 0. |
| Communication | Synchronous โ sender and receiver must synchronize for data transfer. | Asynchronous โ allows data to be queued up to the buffer capacity. |
| Send Operation | Blocks until a receiver is ready to receive the value. | Blocks only when the buffer is full. |
| Receive Operation | Blocks until a sender is ready to send a value. | Blocks only when the buffer is empty. |
package main
import (
"fmt"
"sync"
)
func main() {
nums := []int {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
maxGoRoutines := 3
type Squares struct {
num int
square int
}
result := []Squares{}
// A semaphore is a concurrency primitive that uses a counter to
// limit how many goroutines or threads can access a shared
// resource at the same time.
// In Go, a buffered channel is the most common way to build a
// semaphore because its capacity naturally limits concurrent operations.
sem := make(chan struct{}, maxGoRoutines)
var wg sync.WaitGroup
var mu sync.Mutex
for _, n := range nums {
wg.Add(1)
// Blocks if 3 goroutines are already running
sem <- struct{}{}
go func(n int) {
defer wg.Done()
// Releases the slot in semphore when done
defer func() { <-sem }()
mu.Lock()
result = append(result, Squares{num:n, square: n*n})
mu.Unlock()
} (n)
}
wg.Wait()
var sum int
for _, r := range result {
sum += r.square
}
fmt.Print("Sum of squares:", sum)
}
Output
# go run -race main.go
Sum of squares:2870
package main
import (
"fmt"
"sync"
)
func Worker(numbersChannel <-chan int, resultChannel chan<- int, wg *sync.WaitGroup) {
defer wg.Done()
for n := range numbersChannel {
resultChannel <- n*n;
}
}
func main() {
numCh := make(chan int, 20)
resCh := make(chan int, 20)
var wg sync.WaitGroup
maxGoRoutines := 3
for r:=0; r<maxGoRoutines; r++ {
wg.Add(1)
go Worker(numCh, resCh, &wg)
}
for i:=1; i<=20; i++ {
numCh <- i
}
close(numCh) // No more input values
wg.Wait() // Wait until all workers finish
close(resCh) // No more results will be sent
answer := 0
for result := range resCh {
answer += result
}
fmt.Print("Sum of squares from 1..20 is ", answer)
}
Output
$ go run -race main.go
Sum of squares from 1..20 is 2870
ยฉ 2019-2026 Algotree.org | All rights reserved.
This content is provided for educational purposes. Feel free to learn, practice, and share knowledge.
For questions or contributions, visit algotree.org
"A SQL query walks into a bar, walks up to two tables and asks... 'Can I join you?'"