Task 4 of 6
A kernel's return value doesn't stay on the GPU — awaiting the call hands you the finished result as an ordinary (typed) array. From there it's plain JavaScript: loop over it, sum it, feed it to a chart, whatever you like.
This round trip is the heartbeat of GPGPU: upload → compute in parallel → read back. Here the parallel part computes 128 squares; the read-back part totals them.
x² for each thread, then sum
the returned array in plain JavaScript and log the total with console.log.this.thread.x * this.thread.x for all 128 threadsresult array in ordinary JavaScript — outside the kernel690880)With output: [128], await squares() gives you a
Float32Array of 128 numbers. It's indexable and loopable like any array.
A plain for loop after the kernel call:
let total = 0;
for (let i = 0; i < result.length; i++) {
total += result[i];
}cudaMemcpy device→host and WebGPU's
mapAsync staging buffers exist for exactly this step — and minimizing round trips
is rule one of real GPU performance (Pipelines & Textures makes a whole
meal of it).
This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.