Basis Lab

How a Program Runs on a GPU

The Loop Had an Order and the Sum Never Needed It

A loop over an array becomes one function of an index when no trip needs another trip's result. Two questions decide whether a given loop qualifies.

What the loop was doing for you

Here is a loop that adds two arrays, element by element, into a third. It is about the plainest useful loop there is.

FIG 1Adding two arrays, one trip at a time
cpp
void addLoop(float* A, float* B, float* C, int n) {
    for (int i = 0; i < n; i++) {
        C[i] = A[i] + B[i];
    }
}
The loop supplies two things. One is the work of a single trip, which is the middle line. The other is an order: trip 0, then trip 1, then trip 2. The addition asked for the first and never asked for the second.

Look at what one trip touches. It reads cell i of A and cell i of B, and it writes cell i of C. It reads nothing that any other trip writes, and it writes nothing that any other trip reads or writes. Trip 7 would come out the same if it ran first, last, or at the same moment as trip 300,000.

So the order was never part of the computation. It was a habit of the machine the loop was written for, which had one place to do arithmetic and had to take the trips one after another. A GPU, as Why a GPU Is Built This Way set out, has a great many slower places instead. To use them, the order has to go.

The body, with the loop removed

Take the loop away and keep the middle line. What is left is a function of the index: given i, add those two cells and store the result.

FIG 2The same work as a function of an index
cpp
__global__ void vecAdd(float* A, float* B, float* C, int vectorLength) {
    int workIndex = threadIdx.x + blockIdx.x*blockDim.x;
    if (workIndex < vectorLength) {
        C[workIndex] = A[workIndex] + B[workIndex];
    }
}
This is NVIDIA's C++ dialect, CUDA, as given in the 2026 edition of its programming guide. The marker on the first line says the function is to be launched on the device. There is no loop and no return value. Each worker that runs the function works out its own index on the second line, which is the subject of the next lesson, and the test on the third line is explained there too.

The vendor calls such a function a kernel, and calls each run of it a thread. This course will say function and worker. The program that launches the function asks for as many workers as there are elements, and the guide says plainly that this is often millions. Every worker runs the same few lines. The only thing that differs between them is the index.

The function returns nothing, and that is not an accident of the dialect. A million workers cannot hand back a million return values to one caller. The result of a run is the cell it wrote.

To see that the order really is free, run four workers in a shuffled order over two small arrays, A holding 1, 2, 3, 4 and B holding 10, 20, 30, 40.

FIG 3Four runs in a shuffled order
steprunindexreadsC after the runwhat happened
1123 and 30_, _, 33, _The worker with index 2 happens to go first. It needs nothing from anyone.
2201 and 1011, _, 33, _Index 0 goes second. It fills its own cell and disturbs no other.
3334 and 4011, _, 33, 44Index 3. Still no run has read a cell that another run wrote.
4412 and 2011, 22, 33, 44The last cell fills. The output is exactly what the loop would have produced.
4 steps
There are 24 orders in which four runs can happen, and all 24 end with 11, 22, 33, 44. Since every order gives the same answer, so does running all four at once.

If w workers can run at the same moment, n elements take n divided by w rounds, rounded up. With an illustrative 4,096 workers running at once, 1,048,576 elements take 256 rounds where the loop took 1,048,576 trips.

What stops a loop being written this way

Now change the loop slightly. Instead of adding two arrays, keep a running total: each cell of the output is the sum of every input cell up to that point. The body is one line, the output cell i equals output cell i minus 1 plus input cell i.

It looks just as simple, and it cannot be written as the function above. Trip i reads a cell that trip i minus 1 writes. Trip i minus 1 needs trip i minus

  1. The trips form a chain as long as the array, and a chain has to be walked one link at a time. For 1,048,576 elements that is 1,048,575 links, and 4,096 idle workers do not shorten it by one.

That is the first of two questions to ask of any loop. The second concerns writing. Suppose the loop adds every element into a single total. No trip reads another trip's output cell, but all of them write the same cell. Run two of them together and the cell keeps whichever write landed last.

FIG 4Six loops against the two questions
a trip reads a cell another writestwo trips write one cellone function of the index
adding two arrays001
scaling every element001
averaging neighbours into a new array001
a running total100
summing into one total010
counting values into bins010
A one marks a yes. A loop is one function of the index only when both of the first two columns are zero. The third row reads its neighbours, which is allowed, because it reads them from the input and writes to a separate output. The marked cells are the three failures.

The third row deserves a second look, because it is the commonest mistake in the other direction. Reading other cells is harmless. What matters is whether anyone writes them during the run. Averaging neighbours from an input array into a separate output array passes. Averaging in place, overwriting the same array, fails the first question.

What becomes of the failures

Neither failure is the end of the matter. A carried value can often be rearranged so that the chain becomes a tree, and a tree of 1,048,576 leaves is only 20 levels deep. Two writers on one cell can be made safe with an update that cannot be interrupted. Those are the subjects of Sharing Within a Block and Two Workers, One Cell later in this course.

FIG 5
LoopReads a cell another trip writesTwo trips write one cellFate
Adding two arraysnonoone function, as written
A running totalyesnomust be rearranged first
Summing into one totalnoyesstaged, later in this course
Counting into binsnoyesneeds a protected update

The habit to form is to ask the two questions before writing anything. If both answers are no, delete the loop, keep the body, and let the index come from the worker. If either is yes, the loop as written holds an order that the computation depends on, and the rewrite has to deal with that order rather than discard it.

Recap

  • A loop whose trips each read their own inputs and write their own output can be written as one function of the index, and the runs of that function may then happen in any order or all at once.
  • A loop cannot be written that way when one trip reads a cell that another trip writes, because the chain of results forces an order that no number of workers can shorten.
  • A loop also fails when two trips write the same cell, because the result then depends on which run arrived last, and nothing in the device promises an order.

This is the reading half

Starting the course gives you your own copy of it. Every idea on every page has problems standing under it, marked with a reason rather than a tick, and any sentence you do not believe can be opened and argued with. None of that can happen on a page nobody owns.

The contents

NextWorkers, Blocks and the Grid →

The rest of this course

  1. 01The Loop Had an Order and the Sum Never Needed Ityou are here
  2. 02Nobody Hands a Worker Its Index, So It Works It Out from Where It Sitsopening only
  3. 03One Worker Disagrees and Thirty-One Others Stand and Waitopening only
  4. 04A Group That Is Waiting Does Not Need the Arithmetic Units, So Another Takes Themopening only
  5. 05The Function Asked for a Little More Storage and Half Its Groups Had to Leaveopening only
  6. 06Adding 256 Numbers in Eight Stages, with Everyone Waiting at the End of Eachopening only
  7. 07Two Workers Added One to the Same Cell and It Went Up by Oneopening only
  8. 08The Timer Said the Function Took No Time, Because It Had Not Run Yetopening only

Read alongside