I am trying to synchronize a pair of non-UI threads, one thread to run game logic and one thread to render, in order to execute tasks in a logical and efficient order. A constraint I imposed myself was that the entire system operate at an allocation-free steady state, so all display objects are returned and 'recycled' and therefore the two threads must maintain a sort of two-way dialog, which occurs when I call the 'swapBuffers()' method.
In pseudocode, the order of events in the game thread looks something like this:
while(condition)
{
processUserInput();
runGameLogicCycle(set number of times);
waitForBuffersSwapped();
unloadRecycleBuffer(); //This function modifies one buffer
loadDisplayBuffer(); ///This function modifies another buffer
waitForRenderFinished();
renderThread.postTask(swapBuffersAndRender);
}
The render thread is chosen to do the task of swapping buffers such that the game logic thread can do tasks in the meantime that do not modify the buffers. In my code, I combine the task of swapping buffers and rendering and define it as a Runnable object which is posted to the render thread's handler. In pseudocode, that runnable looks something like this:
{
//Swap the buffers
}
gameThread.notifyThatBuffersSwapped();
{
//Render items to screen
}
gameThread.notifyThatItemsRendered();
My problem is an implementation problem. I am familiar with the concepts of handlers, synchronization blocks, and ReentrantLocks. I am aware of the Lock.await() Lock.signal() methods, but I find the documentation insufficient when trying to understand how they behave when called in an iterating loop.
How does one implement ReentrantLocks to make two threads wait on each other in such a way? Please include a practical idiom in your answer if possible.