This is a start on a multi-threaded game loop and I just wish to confirm my code is going in the correct direction, and if not, if there is any way it can be improved. I have good experience in game development and C++ in general, but limited experience when it comes to multi-threaded environments.
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <memory>
#include <chrono>
class Test
{
public:
Test()
{
std::cout << "Test starting" << std::endl;
start();
}
~Test()
{
stop();
std::cout << "Test finished" << std::endl;
}
inline void quit()
{
running = false;
}
private:
void start()
{
renderThread = std::unique_ptr<std::thread>(new std::thread(&Test::renderFunc, this));
updateThread = std::unique_ptr<std::thread>(new std::thread(&Test::updateFunc, this));
std::cout << "Threads Created" << std::endl;
running = true;
}
void stop()
{
renderThread->join();
updateThread->join();
std::cout << "Threads joined" << std::endl;
}
void updateFunc()
{
while(running)
{
mutex.lock();
std::cout << "update" << std::endl;
mutex.unlock();
}
}
void renderFunc()
{
while(running)
{
mutex.lock();
std::cout << "render" << std::endl;
mutex.unlock();
}
}
volatile bool running;
std::mutex mutex;
std::unique_ptr<std::thread> renderThread;
std::unique_ptr<std::thread> updateThread;
};
int main(int argc, char* argv[])
{
std::unique_ptr<Test> test = std::unique_ptr<Test>(new Test());
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::seconds Seconds;
Clock::time_point t0, t1;
Seconds seconds;
t0 = Clock::now();
do
{
t1 = Clock::now();
seconds = std::chrono::duration_cast<Seconds>(t1 - t0);
}while(seconds.count() <= 15);
test->quit();
return 0;
}
(The timer code is just there for testing the threaded code.)
terminate called after throwing an instance of 'std::system_error' what(): Operation not permitted
\$\endgroup\$