c++ - Separate physics thread without locks -
i have classic physics-thread vs. graphics-thread problem:
say i'm running 1 thread physics update , 1 thread rendering.
in physics thread (pseudo-code):
while(true) { foreach object in simulation somecomplicatedphysicsintegration( &object->modelviewmatrix); //modelviewmatrix vector of 16 floats (ie. 4x4 matrix) } and in graphics thread:
while(true) { foreach object in simulation renderobject(object->modelviewmatrix); } now in theory not require locks, 1 thread writing matrices , reading, , don't care stale data much.
the problem updating matrix not atomic operation , graphics thread read partially updated matrices (ie. not 16 floats have been copied, part of them) means part of matrix 1 physics frame , part previous frame, in turn means matrix nolonger affine (ie. it's corrupted).
is there method of preventing without using locks? read possible implementation using double buffering, cannot imagine way work without syncing threads.
edit: guess i'd use sort of triple buffering use on graphic displays.. know of presentation of triple buffering algorithm?
edit 2: indeed using non-synced triple buffering not ideea (as suggested in answers below). physics thread can run mutiple cycles eating lot of cpu , stalling graphics thread, computing frames never rendered in end.
i have opted simple double-buffered algorithm single lock, physics thread computes as 1 frame in advance of graphics thread before swapping buffers. this:
physics:
while(true) { foreach physicstimestep foreach object in simulation somecomplicatedphysicsintegration( &object->modelviewmatrix.writebuffer); locksemaphore() swapbuffers() unlocksemaphore() } graphics:
while(true) { locksemaphore() foreach object in simulation renderobject(object->modelviewmatrix.readbuffer); unlocksemaphore() } how sound?
but cannot imagine way work without syncing threads.
no matter kind of scheme using, synchronizing threads absolute essential here. without synchronization run risk physics thread race far ahead of graphics thread, or vice versa. program, typically master thread advances time, needs in control of thread operations, not threading mechanism.
double buffering 1 scheme lets physics , graphics threads run in parallel (for example, have multi-cpu or multi-core machine). physics thread operates on 1 buffer while graphics thread operates on other. note induces lag in graphics, may or may not issue.
Comments
Post a Comment