From d20633705e53a122467fb39fdbb2de3cfec279f7 Mon Sep 17 00:00:00 2001 From: Clyne Sullivan Date: Sat, 14 Jan 2017 12:48:49 -0500 Subject: thread work --- main.cpp | 76 +++++++++++++++++++++++++++++++++++++++------------------------- 1 file changed, 47 insertions(+), 29 deletions(-) (limited to 'main.cpp') diff --git a/main.cpp b/main.cpp index 2e5e69d..49199a0 100644 --- a/main.cpp +++ b/main.cpp @@ -21,6 +21,31 @@ using namespace std::literals::chrono_literals; #include #include +class GameThread : public entityx::Receiver { +private: + std::atomic_bool die; + bool running; + std::thread thread; + +public: + template + GameThread(F&& func) { + die.store(false); + running = true; + thread = std::thread([this](F&& f) { + while (!die.load()) + f(); + running = false; + }, std::forward(func)); + } + + void stop(void) { + die.store(true); + while (running) + std::this_thread::sleep_for(2ms); + } +}; + /** * The currently used folder to look for XML files in. */ @@ -112,43 +137,36 @@ int main(int argc, char *argv[]) if (!worldDontReallyRun) { // the main loop, in all of its gloriousness... - std::thread thMain ([&] { - const bool &run = game::engine.shouldRun; - while (run) { - game::time::mainLoopHandler(); - - if (game::time::tickHasPassed()) { - // calculate the world shading value - extern int worldShade; // TODO kill - worldShade = 50 * sin((game::time::getTickCount() + (DAY_CYCLE / 2)) / (DAY_CYCLE / PI)); + GameThread gtMain ([&] { + game::time::mainLoopHandler(); - // update fades - ui::fadeUpdate(); + if (game::time::tickHasPassed()) { + // calculate the world shading value + extern int worldShade; // TODO kill + worldShade = 50 * sin((game::time::getTickCount() + (DAY_CYCLE / 2)) / (DAY_CYCLE / PI)); - // increment game ticker - game::time::tick(); - } + // update fades + ui::fadeUpdate(); - while (!eventQueue.empty()) { - game::events.emit(eventQueue.back()); - eventQueue.pop_back(); - } - - game::engine.update(game::time::getDeltaTime()); + // increment game ticker + game::time::tick(); + } - std::this_thread::sleep_for(1ms); + while (!eventQueue.empty()) { + game::events.emit(eventQueue.back()); + eventQueue.pop_back(); } + + game::engine.update(game::time::getDeltaTime()); + std::this_thread::sleep_for(1ms); }); static int fps = 0, fpsInternal = 0; // the debug loop, gets debug screen values - std::thread thDebug ([&] { - const bool &run = game::engine.shouldRun; - while (run) { - fps = fpsInternal, fpsInternal = 0; - std::this_thread::sleep_for(1s); - } + GameThread gtDebug ([&] { + fps = fpsInternal, fpsInternal = 0; + std::this_thread::sleep_for(1s); }); // the render loop, renders @@ -163,8 +181,8 @@ int main(int argc, char *argv[]) } // on game end, get back together - thMain.join(); - thDebug.join(); + gtMain.stop(); + gtDebug.stop(); //game::engine.getSystem()->thAmbient.join(); // segfault or something } -- cgit v1.2.3