Task 2 of 6

Gather: Read Anywhere

A map reads its own cell. A gather reads any cell — the thread computes where to read from using its own index. Reads are random-access and cheap; it's only writes that are pinned to your own cell (the next task is all about that).

The cleanest possible gather: reverse an array. Thread 0 pulls the last element, thread 63 pulls the first — every thread reads exactly one cell, just not its own. The array length is wired in as this.constants.n, so the kernel doesn't hardcode 64.

Goal: make the kernel return the element from the mirrored position, so the output is data reversed.

Requirements

Hint 1 — mirror arithmetic

The mirror of index i in an n-element array is n − 1 − i: index 0 ↔ index 63, index 1 ↔ index 62, …

Hint 2 — the one-liner
return data[this.constants.n - 1 - this.thread.x];

Same idea elsewhere

Gather is why GPUs have texture units: shaders sample textures at arbitrary coordinates, CUDA routes scattered reads through __ldg and texture memory, WebGPU compute shaders index storage buffers freely. Hardware is built to make "read from anywhere" fast.

All tasks in Thinking in Parallel

  1. Map: One Thread, One Value
  2. Gather: Read Anywhere
  3. No Scatter Allowed
  4. Life on the Edge
  5. Smooth a Signal
  6. The Two-Pass Blur

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.