# The One-Thread Trap

*Task 1 of 6 · [Reductions](https://gpu.rocks/learn/reductions-3dadc130.md) · GPU.js Learn*

Meet the **reduction**: many values in, one value out — sum, min,
max, mean. It's the awkward case in GPU land, because a kernel thread writes exactly
*one* output cell. 4,096 inputs collapsing to 1 output means
`output: [1]`… a single thread.

You *can* do it — kernels may loop, as long as the bound is known at compile
time, which is exactly what `this.constants` is for. But one thread grinding
through 4,096 additions while thousands of its neighbours sit idle is the slowest
possible way to use a GPU. Write it anyway: it's the baseline the rest of this module
tears down.

## Goal

**Goal:** make the single thread loop over all of `data`
(bound: `this.constants.n`) and return the total.

## Requirements

- Keep `output: [1]` — one thread owns the one output cell
- Loop `for (let i = 0; i < this.constants.n; i++)` — in gpu.js's WebGL backend, loop bounds must be compile-time constants
- Accumulate into a local `let sum` and return it

## Hint 1 — an accumulator

Declare `let sum = 0;` before the loop, add to it inside the loop,
and `return sum;` after. Plain JavaScript — the transpiler handles it.

## Hint 2 — the loop body

One statement: `sum += data[i];`

## Same idea elsewhere

This wall exists on every platform: a single CUDA thread summing a whole buffer
is the textbook example of what *not* to do, and a naive WebGPU compute shader
with one invocation hits it just the same. Everyone's escape route is the trick you
build next — split the work, then combine.

## Starter code

```js
// 4096 values, ONE output cell — so exactly one thread does everything.
const gpu = new GPU({ mode });

const sumAll = gpu.createKernel(function (data) {
  // TODO: loop i from 0 to this.constants.n, accumulate data[i]
  // into a local sum, and return it.
  return 0;
}, {
  output: [1],
  constants: { n: 4096 },
});

console.log('total:', (await sumAll(data))[0]);
```

---

Interactive version: https://gpu.rocks/learn/reductions-3dadc130/1

[Next task](https://gpu.rocks/learn/reductions-3dadc130/2.md)
