title: Structuring and Synchronizing a Multithreaded Game Loop
body: <p>I'm running into a mild conundrum concerning thread safety for my game loop. What I have below is 3 threads (including the main) that are meant to work together. One for event managing (main thread), one for logic, and one for the rendering. All 3 of these threads exist within their own class, as you can see below. In basic testing the structure works without problems. This system uses SFML and renders with OpenGL. </p>
  
  <pre><code>int main(){
      Gamestate gs;
      EventManager em(&amp;gs);
      LogicManager lm(&amp;gs);
      Renderer renderer(&amp;gs);
  
      lm.start();
      renderer.start();
      em.eventLoop();
  
      return 0;
  }
  </code></pre>
  
  <p>However, as you may have noticed I have a "Gamestate" class that is meant to act as a container of all the resources that need to be shared between the threads (mostly with LogicManager as a writer and Renderer as a reader. EventManager is mostly just for window events). My questions are: (1 and 2 being the most important)</p>
  
  <p>1) Is this a good way of going about things? Meaning is having a "global" Gamestate class a good idea to use? Is there a better way of going about it?</p>
  
  <p>2) My intention was to have Gamestate have mutexes in the getters/setters, except that doesn't work for reading because I can't return the object while it's still locked, which means I'd have to put synchronization outside of the getters/setters and make the mutexes public. It also means I'd have a bloody ton of mutexes for all the different resources. What is the most elegant way of going about this problem?</p>
  
  <p>3) I have all of the threads accessing "bool run" to check if to continue their loops</p>
  
  <pre><code>while(gs-&gt;run){
  ....
  }
  </code></pre>
  
  <p>run gets set to false if I receive a quit message in the EventManager. Do I need to synchronize that variable at all? Would I set it to volatile?</p>
  
  <p>4) Does constantly dereferencing pointers and such have an impact on performance? eg gs->objects->entitylist.at(2)->move(); Do all those '->' and '.' cause any major slowdown?</p>