Hello!
This is an excellent example problem you posted here, because you have made a mistake that every programmer must make in his life to learn from it: synchronisation in multithreading.
First of all, it’s a good idea to use multiple threads to separate work:
RenderSystem myRenderSystem; // create render system
std::thread RenderSystemLoop(&RenderSystem::StartLoop , &myRenderSystem); // start our system
std::thread LoadModel(&RenderSystem::Add3DMesh, &myRenderSystem, &MeshInfoFormatID, &MeshID, &vertices[0], sizeof(vertices), true); // load 3d mesh
// std::cout << VertexShaderSource <<std::endl;
std::thread LoadShader(&RenderSystem::AddShader, &myRenderSystem, &VertexShaderSource, &FragmentShaderSource, &shaderProgram);
std::thread DrawData(&RenderSystem::Draw3DMesh, &myRenderSystem, &MeshInfoFormatID, &shaderProgram);
LoadShader.join();
DrawData.join();
LoadModel.join();
RenderSystemLoop.join();
It’s also nice you are using C++11. There is only one big problem: Your code does not yet contain any synchronisation like std::mutex
, std::shared_mutex
or std::conditional_variable
.
See, when you are using DrawData, you must make sure that LoadModel and LoadShader are finished, otherwise the function throws an exception and the program crashes. This waiting for other stuff to be ready is not being done automatically for you in C++.
But there are more things you must consider when using multiple threads: 2 (or more) threads can never write to the same data or read/write from it. You must use std::mutex
or std::shared_mutex
to control that only one thread has write access to the data at the same time. 2 or more threads can read from the same data at the same time without problem though, it’s about the write/write and write/read that causes problems.
Synchronisation in multithreading is tricky, because you have to think a lot about your program structure and the possible combination of errors that could occur is huge. I get a different error every time I run your program because the order of which threads are executed is not defined! You have to synchronise it with the techniques I mentioned yourself.
To solve this, you must think about which variables are read or written from which threads and protect them. I wanted to show you a solution but I have to think about it as well for a moment.
Check out tutorial about synchronisation like mutex, shared_mutex and conditional_variable.
Johannes.