liveBook · Manning

Parallel merge sort

As explained in 100 Go Mistakes and How to Avoid Them

A merge sort implementation that processes independent sublists concurrently.

Parallel merge sort divides a list into independent slices, sorts the halves concurrently in goroutines, waits with sync.WaitGroup, and merges them afterward. The structure permits concurrency, but creating goroutines for every recursive split can cost more than it saves. section 8.2.2

The small-task mistake

On 10,000 elements, the unrestricted parallel version takes 17,525,998,709 ns/op versus 2,278,993,555 ns/op sequentially. A cutoff at 2,048 elements lets smaller partitions use sequentialMergesort; the benchmark falls to 1,313,010,260 ns/op.

const max = 2048                      #1
 
func parallelMergesortV2(s []int) {
    if len(s) <= 1 {
        return
    }
 
    if len(s) <= max {
        sequentialMergesort(s)        #2
    } else {                          #3
        middle := len(s) / 2
 
        var wg sync.WaitGroup
        wg.Add(2)
 
        go func() {
            defer wg.Done()
            parallelMergesortV2(s[:middle])
        }()
 
        go func() {
            defer wg.Done()
            parallelMergesortV2(s[middle:])
        }()
 
        wg.Wait()
        merge(s, middle)
    }
}

Inspect the cutoff implementation that limits goroutine creation and delegates small partitions to sequential merge sort. section 8.2.2

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Explains recursive splitting, goroutine coordination, merging, benchmarks, and a workload cutoff, without presenting the most efficient implementation.
Examples
Uses sequential and parallel Go implementations, a four-core benchmark, and a 2,048-element cutoff.
What it assumes
Assumes familiarity with recursive merge sort, Go slices, goroutines, and sync.WaitGroup.
What you can do after
Evaluate parallel merge-sort designs with benchmarks and apply a cutoff when goroutine overhead dominates useful work.
How it connects
Connects merge sort with goroutines, slices, CPU cores, and sync.WaitGroup.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.