I want my rendering to be multithreading. Also I want window events to run simultaneously with rendered things. I do not know much about sfml, so the first thing that I came into was to create a new thread that runs in parallel with the event loop like this:
void renderingThread(sf::Window* window)
{
while (window->isOpen())
{
}
}
int main()
{
sf::ContextSettings contextSettings;
contextSettings.depthBits = 24;
contextSettings.majorVersion = 4;
contextSettings.majorVersion = 6;
contextSettings.attributeFlags = contextSettings.Core;
sf::Window window(sf::VideoMode(640, 480), "SFML window with OpenGL", sf::Style::Default, contextSettings);
window.setActive(false);
std::thread t1([&window]() {
renderingThread(&window);
});
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed)
window.close();
if ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape))
window.close();
}
}
t1.join();
return EXIT_SUCCESS;
}
Now I have to create another 2 threads - the first one to queue/push gl commands and the second one to dequeue/pop/actually run gl commands. To simplify this I create a one new thread that just color and clear default frame buffer. It is clear that I have to active context and swap windows/buffers, so methods
window->setActive(true);
and
window->Display();
are called.
void renderingThread(sf::Window* window)
{
while (window->isOpen())
{
std::thread thread([&window]() {
window->setActive(true);
glClearColor(1, 1, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
window->display();
});
}
}
cpp
When I run this code, memory rises every second. `window->setActive(true);` is the problem.
How can I fix this problem and achive similar effect?
Do I do something wrong? How are more advanced systems implemented?
To visual a bit more what I'd like to achive I show here a pseudo code
void renderingThread(sf::Window* window)
{
std::atomic_bool simulationDone = false;
while (window->isOpen())
{
std::thread simulationThread([]() {
//Updatelogic
//it's a thread-safe queue
//queue up gl calls
renderQueue.push(new CmdClearColor(1, 1, 1, 1));
renderQueue.push(new CmdClear(COLOR_BUFFER_BIT));
simulationDone.store(true);
});
std::thread renderThread([&window]() {
window->setActive(true);
while(!(renderQueue.empty() && simulationDone.load())) {
Cmd* cmd = nullptr;
if(renderQueue.pop(cmd)) {
//do gl calls
cmd->DoCmd();
}
}
window->display();
});
simulationThread.join();
renderThread.join();
}
}