Adding multithreading to our games
We will now modify our Gravitris to paralyze the physics calculations from the rest of the program. We will need to change only two files: Game.hpp
and Game.cpp
.
In the header file, we will not only need to add the required header, but also change the prototype of the update_physics()
function and finally add some attributes to the class. So here are the different steps to follow:
Add
#include <SFML/System.hpp>
, this will allow us to have access to all the classes needed.Then, change the following code snippet:
void updatePhysics(const sf::Time& deltaTime,const sf::Time& timePerFrame);
to:
void updatePhysics();
The reason is that a thread is not able to pass any parameters to its wrapped function so we will use another solution: member variables.
Add the following variables into the
Game
class as private:sf::Thread _physicsThread; sf::Mutex _mutex; bool _isRunning; int _physicsFramePerSeconds;
All these variables will be used by the physics thread...