5
\$\begingroup\$

I have been reading a lot about this, but still not sure about a proper way to implement an independent render thread, using a variable time step and running in parallel to a physics thread, which uses a smaller, fixed time step. I'm familiar with the mechanics of mutexes and locking, when it comes to concurrent write access, but a render function would only read, and never modify.

Would a locking mechanism be required, at all, for using two buffers - a read buffer that is used by the renderer, while the physics engine modified the write buffer, and swapping after it's finished?

Even with only one buffer, I could imagine that you wouldn't even notice when some objects are updated, while rendering, having interpolation anyway and the much higher render frame rate. The only problem I see, with one buffer, is when objects would be deleted from physics and the renderer still trys to access them.

What is the main problem there? I am not talking about, for example, a concurrent physics and AI that both modify - only one additional render thread.

\$\endgroup\$
4
\$\begingroup\$

Technically reading a value that another thread is writing to is undefined behavior. This means that anything is allowed to happen up to and including nasal demons or getting your harddrive formatted.

In reality it usually means the reading thread gets a corrupt value. This can cause visual artifacts like flickering models. Or if the value read is a pointer or pointer offset (and you don't do a bounds check) then a segfault is possible. Also the optimizer is allowed to reorder your memory accesses unless you explicitly prevent it and doing that screws with the optimizer.

To fully fix it you need 3 buffers.

  • The physics thread uses 2. One as read-only for the current state and one in write for the next state. When the physics pass is complete the buffer in write state becomes read-only and it then picks the remaining buffer that the render thread isn't currently reading for the write buffer. At this point all 3 buffers will be in use.

  • The render thread uses a read-only buffer to render and when the render pass is done, it will pick the buffer the physics thread is reading from. This may be the same as the previous render buffer if rendering is outspeeding the physics thread.

In my limited experience with atomics I haven't found a way to have the threads pick their buffers without needing a lock. But the critical section is only a few memory operations so it's not a huge deal (a busy-wait lock would suffice most of the time).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.