Stalls part two: beware of SetData

Originally posted to Shawn Hargreaves Blog on MSDN, Tuesday, April 15, 2008

ajmiles got it in one.

This harmless looking code:

    vertexBuffer.SetData(particlePositions);
    graphicsDevice.VertexBuffer = vertexBuffer;
    graphicsDevice.DrawPrimitives(...);

will cause a pipeline stall if the CPU reaches the SetData call for frame #2 before the GPU finishes processing the DrawPrimitives call from frame #1.

This occurs because resources such as vertex buffers and textures are passed by reference, not by value. You can think of each resource as a separate piece of paper filled with data:

This is efficient, because Charles does not have to bother touching the actual vertex data while processing the draw instruction.

But what if the game later calls SetData on this same vertex buffer?

If the GPU is still using the resource, the second SetData call must stall until it has finished.

There are several ways to avoid such a stall:

Blog index   -   Back to my homepage