Concurrency and Packages
Goroutine Result Slots
Workers can run concurrently while writing results into stable slots that the main goroutine reads after all workers finish.
Goroutine Result Slots
goroutine_result_slots.go
package main
import (
"fmt"
"sync"
)
func main() {
var workerCount =
results := make([]int, workerCount)
var wg sync.WaitGroup
for index := 0; index < workerCount; index++ {
wg.Add(1)
go func(slot int) {
defer wg.Done()
base := slot + 1
results[slot] = base * 10
}(index)
}
wg.Wait()
total := 0
for _, value := range results {
total += value
}
fmt.Println("workers=", workerCount)
fmt.Println("results=", results)
fmt.Println("total=", total)
}
package main
import (
"fmt"
"sync"
)
func main() {
var workerCount =
results := make([]int, workerCount)
var wg sync.WaitGroup
for index := 0; index < workerCount; index++ {
wg.Add(1)
go func(slot int) {
defer wg.Done()
base := slot + 1
results[slot] = base * 10
}(index)
}
wg.Wait()
total := 0
for _, value := range results {
total += value
}
fmt.Println("workers=", workerCount)
fmt.Println("results=", results)
fmt.Println("total=", total)
}
package main
import (
"fmt"
"sync"
)
func main() {
var workerCount =
results := make([]int, workerCount)
var wg sync.WaitGroup
for index := 0; index < workerCount; index++ {
wg.Add(1)
go func(slot int) {
defer wg.Done()
base := slot + 1
results[slot] = base * 10
}(index)
}
wg.Wait()
total := 0
for _, value := range results {
total += value
}
fmt.Println("workers=", workerCount)
fmt.Println("results=", results)
fmt.Println("total=", total)
}
result slots
Use a `WaitGroup` and one array slot per worker so final output is deterministic even when goroutines run in different orders.