Search code examples
c++multithreadingopengltimingglew

C++ - Execute function every X milliseconds


I can't seem to find a good answer to this:

I'm making a game, and I want the logic loop to be separate from the graphics loop. In other words I want the game to go through a loop every X milliseconds regardless of how many frames/second it is displaying.

Obviously they will both be sharing a lot of variables, so I can't have a thread/timer passing one variable back and forth... I'm basically just looking for a way to have a timer in the background that every X milliseconds sends out a flag to execute the logic loop, regardless of where the graphics loop is.

I'm open to any suggestions. It seems like the best option is to have 2 threads, but I'm not sure what the best way to communicate between them is, without constantly synchronizing large amounts of data.


Solution

  • You can very well do multithreading by having your "world view" exchanged every tick. So here is how it works:

    1. Your current world view is pointed to by a single smart pointer and is read only, so no locking is necessary.
    2. Your logic creates your (first) world view, publishes it and schedules the renderer.
    3. Your renderer grabs a copy of the pointer to your world view and renders it (remember, read-only)
    4. In the meantime, your logic creates a new, slightly different world view.
    5. When it's done it exchanges the pointer to the current world view, publishing it as the current one.
    6. Even if the renderer is still busy with the old world view there is no locking necessary.
    7. Eventually the renderer finishes rendering the (old) world. It grabs the new world view and starts another run.
    8. In the meantime, ... (goto step 4)

    The only locking you need is for the time when you publish or grab the pointer to the world. As an alternative you can do atomic exchange but then you have to make sure you use smart pointers that can do that.