Nobody Hands a Worker Its Index, So It Works It Out from Where It Sits
Last timeOne Function, Run a Million Times
Workers come in equal blocks, and blocks come in a grid. A worker finds its element from two positions, and one integer division picks a block count that covers any length.
Where the index comes from
The last lesson ended with a function of an index and left one line unexplained. In a loop the index is handed over by the loop. Here there is no loop, and a million workers all start the same function with the same arguments. Each has to find out which element is its own.
The device tells a worker only where it sits. Workers are launched in equal blocks, and the blocks are laid out in a row called the grid. A worker can ask three things: its position inside its block, its block's position in the grid, and the size of a block. From those it builds the index itself.
- the index of the element this worker handles
- the position of the worker's block in the grid, counting from zero
- the number of workers in every block
- the worker's position inside its own block, counting from zero
The multiplication skips the elements that belong to earlier blocks. Three blocks come before block 3, each covering 256 elements, so block 3 starts at element 768. The worker then counts 17 further along.
A small case makes the pattern visible. Take blocks of only 4 workers and an array of 14 elements.
| position 0 | position 1 | position 2 | position 3 | |
|---|---|---|---|---|
| block 0 | 0 | 1 | 2 | 3 |
| block 1 | 4 | 5 | 6 | 7 |
| block 2 | 8 | 9 | 10 | 11 |
| block 3 | 12 | 13 | 14 | 15 |
The positions can also be given in two or three dimensions, which suits images and volumes. The vendor's guide says this is for convenience only, and the arithmetic is the same idea with more terms. This course stays with one.
The lesson stops here
4 more paragraphs to go
You have read the opening. The rest of the argument, the problems that check whether it landed, and the lines worth keeping at the end all come with a plan.
The first lesson of every course in the library reads the whole way through, free, so you can see exactly what the rest of them are.
See the planThe contentsThis 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