# Gather: Read Anywhere

*Task 2 of 6 · [Thinking in Parallel](https://gpu.rocks/learn/thinking-in-parallel-c3876efb.md) · GPU.js Learn*

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

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

## Requirements

- Compute the read index from `this.thread.x` and `this.constants.n`
- Thread `i` reads `data[n − 1 − i]`
- No loops, no temporary arrays — one read per thread

## 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

```js
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.

## Starter code

```js
// A gather kernel computes WHERE to read from its own thread id.
const gpu = new GPU({ mode });

const reverse = gpu.createKernel(function (data) {
  // TODO: read the element from the OTHER end of the array.
  // The array length is available as this.constants.n.
  return data[this.thread.x];
}, {
  output: [64],
  constants: { n: 64 },
});

const result = await reverse(data);
console.log('first:', result[0], '(should be the old last:', data[63] + ')');
```

---

Interactive version: https://gpu.rocks/learn/thinking-in-parallel-c3876efb/2

[Previous task](https://gpu.rocks/learn/thinking-in-parallel-c3876efb/1.md) · [Next task](https://gpu.rocks/learn/thinking-in-parallel-c3876efb/3.md)
