Skip to main content

Parallel map in Go with sync.WaitGroup

· 5 min read
Yaroslav Grebnov
Golang developer, SDET

This interview exercise starts with a concurrent map and adds the invariants interviewers commonly ask about: stable order, identifiable results, bounded concurrency, cancellation, and panic recovery.

The final implementation returns one result for every input. A failed or panicking task does not hide the results of other tasks.

Task​

Initial task​

Implement a generic ParallelMap that applies fn to every item concurrently and waits for all tasks to finish.

Follow-up 1: stable and identifiable results​

Return results in the same order as the inputs. Keep the input index with each value or error so a result remains identifiable if it is later separated from the slice.

Follow-up 2: bounded concurrency and cancellation​

Limit active calls to fn. A task waiting for capacity must stop when the context is canceled, and a running task must receive the same context.

Follow-up 3: panic isolation​

Convert a panic from one task into an error for that item. Other tasks must still finish.

The code below is the final version after all follow-ups. It uses Go 1.25, as specified in the example module.

Solution​

package main

import (
"context"
"errors"
"fmt"
"runtime"
"sync"
)

// Result keeps an output, error, and input identity together. The result slice
// preserves input order; i still identifies a result after it leaves that slice.
// If identity and per-item errors are unnecessary, ParallelMap can return []R instead.
type Result[R any] struct {
i int
v R
e error
}

func ParallelMap[T, R any](
ctx context.Context,
items []T,
concurrency int,
fn func(context.Context, T) (R, error),
) []Result[R] {
n := len(items)

if n == 0 {
return []Result[R]{} // for convenience, if caller appends
}

if concurrency <= 0 {
// NumCPU is a reasonable CPU-work default. I/O workloads often benefit from
// a different measured limit because they spend time waiting, not computing.
concurrency = runtime.NumCPU()
}
if concurrency > n {
concurrency = n // no need for more slots than items
}

// Preallocation preserves order and avoids append synchronization. Concurrent
// writes to distinct elements are safe; shared state inside fn may still race.
results := make([]Result[R], n)

// The buffered channel is a semaphore: at most concurrency calls to fn run.
// This still creates O(n) goroutines. For very large inputs, a fixed worker pool
// can bound goroutine and stack overhead as well as active work.
sem := make(chan struct{}, concurrency)

var wg sync.WaitGroup

for i := range n {
results[i].i = i
// Add must happen before go. Adding inside the goroutine can race with Wait;
// forgetting Done would make Wait block forever.
wg.Add(1)
// Pass i explicitly so the input and output slot are visibly paired. Go 1.22+
// also gives each range iteration its own variable, but explicit capture remains clear.
go func(i int) {
defer wg.Done()

select {
case sem <- struct{}{}: // acquire a slot
defer func() { // release the slot even if fn panics
<-sem
}()
case <-ctx.Done():
results[i].e = ctx.Err()
return
}

// recover works only in a deferred function on the goroutine that panics.
// Without it, one task panic terminates the whole program.
defer func() {
if rErr := recover(); rErr != nil {
results[i].e = fmt.Errorf("execution panicked at index %d: %v", i, rErr)
}
}()

// Cancellation may happen while this goroutine waits for the semaphore.
// Check again before fn. Cancellation is cooperative: if it happens after
// this check, fn must observe ctx itself or the task will continue running.
select {
case <-ctx.Done():
results[i].e = ctx.Err()
return
default:
}

// Keep this item's error; another item's failure does not stop the group.
results[i].v, results[i].e = fn(ctx, items[i])
}(i)
}

// Wait establishes that every result write is complete before the slice is read.
// WaitGroup only counts completion and returns no error, so `if err := wg.Wait()`
// is impossible. Each task error has already been stored in results[i].
wg.Wait()

return results
}

var ErrTest = errors.New("ErrTest")

// task simulates success, an ordinary error, and a panic for the demo.
func task(ctx context.Context, i int) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
default:
}

if i == 2 {
return 0, ErrTest
}
if i == 3 {
panic("panic")
}

return i * i, nil
}

The slice position is what preserves order. The i field provides identity after a result is removed from the slice. If the caller only needs ordered values, the field can be removed. If one error should cancel the entire operation, the errgroup version has a better return contract.

Demo​

func demoParallelMap() {
ctx := context.Background()
items := []int{1, 2, 3, 4}
res := ParallelMap(ctx, items, 3, task)
for i := range res {
fmt.Printf("index: %d, value: %d, error: %v\n", res[i].i, res[i].v, res[i].e)
}
}

func main() {
demoParallelMap()
}

Test​

The nominal test covers a successful task, an ordinary error, a recovered panic, and stable output order.

package main

import (
"context"
"errors"
"reflect"
"testing"
)

func TestParallelMap(t *testing.T) {
tests := []struct {
name string
items []int
expected []Result[int]
}{
{
name: "nominal",
items: []int{1, 2, 3, 4},
expected: []Result[int]{
{i: 0, v: 1},
{i: 1, e: ErrTest},
{i: 2, e: errors.New("execution panicked at index 2: panic")},
{i: 3, v: 16},
},
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
actual := ParallelMap(context.Background(), test.items, 3, task)
if len(actual) != len(test.expected) {
t.Fatalf("expected %d results, but got: %d", len(test.expected), len(actual))
}

for i := range test.expected {
if !reflect.DeepEqual(test.expected[i], actual[i]) {
t.Fatalf("expected result at index %d to be %+v, but got: %+v", i, test.expected[i], actual[i])
}
})
}
}

Run the test with the race detector because the implementation writes from multiple goroutines:

$ go test -race -count=1 ./...
ok github.com/ygrebnov/test-concurrency6

Output example​

$ go run .
index: 0, value: 1, error: <nil>
index: 1, value: 0, error: ErrTest
index: 2, value: 0, error: execution panicked at index 2: panic
index: 3, value: 16, error: <nil>

Completion order may differ internally, but the preallocated result slots keep the output deterministic. A value next to a non-nil error is the type's zero value and should not be consumed as a successful result.