Advertisement

Render Thread and Update Thread with D3D11 DXGI

Started by November 13, 2022 11:18 PM
0 comments, last by peter25 2 years ago

Main Thread: window, message pump and D3D11 DXGI. Render frame N.
Background thread: game logic and physics. Update frame N + 1.
Threadpool: worker threads.

It would be extremely helpful if someone could have a look at my first attempt to separate the work between the Main Thread and Background Thread. Do you have any suggestions for improvement to this threading model?

//Render frame N
void render_MainThread()
{
	createWindow();
	createD3D11Resources();
	
	int inputBufferIndex = 0; //[0, 1]
	int gameStateBufferIndex = 0; //[0, 1]
	
	while(!shouldClose())
	{
		waitForUpdateThread();
		
		//PeekMessage(...)
		pumpMessagesOS(inputBufferIndex);
		
		//The update thread will have the latest keyboard and mouse events.
		signalUpdateThread();
		
		//Update GPU data
		//Draw calls
		//Swapchain Present
		render(gameStateBufferIndex);
		
		inputBufferIndex = 1 - inputBufferIndex;
		gameStateBufferIndex = 1 - gameStateBufferIndex;
	}
	
	exitApp.store(true); //Atomic
}

//Update frame N + 1
void update_BackgroundThread()
{
	createGameWorld();
	
	int inputBufferIndex = 1; //[0, 1]
	int gameStateBufferIndex = 0; //[0, 1]
	
	while(!exitApp)
	{
		updateGameLogic(inputBufferIndex);
		updatePhysics();
		updateGameState(gameStateBufferIndex);
		
		inputBufferIndex = 1 - inputBufferIndex;
		gameStateBufferIndex = 1 - gameStateBufferIndex;
		
		//The render thread will have the latest game state.
		signalRenderThread();
		waitForRenderThread();
	}
}

We could try this threading model instead:
Main Thread: window, message pump, game logic and physics.
Background thread: D3D11 DXGI.
Threadpool: worker threads.

But this model is dangerous, because of the way DXGI works. Can easily lead to deadlock and other nasty stuff.

See:
https://learn.microsoft.com/en-us/windows/win32/direct3darticles/dxgi-best-practices#multithreading-and-dxgi
https://learn.microsoft.com/en-us/windows/win32/direct3ddxgi/d3d10-graphics-programming-guide-dxgi#multithread-considerations

Another threading model:
Main Thread: window, message pump.
Update thread: game logic and physics.
Render thread: D3D11 DXGI.
Threadpool: worker threads.

I now know how to avoid deadlock with this threading model, but this model needs a lot of work to get everything right. This model has the advantage of being able to timestamp each input message, which means that we can apply input per fixed update (fixed time-step) instead of per frame.

This topic is closed to new replies.

Advertisement