Here is a complete minimal example:
#include <iostream>
#include <SFML/Graphics.hpp>
void tfunction()
{
long counter = 0;
for(int i=0; i<10000; i++)
{
for(int j=0; j<10000; j++)
{
counter++;
}
}
std::cout << "Counter: " << counter << std::endl;
}
int main ( int argc, char** argv )
{
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML thread example");
sf::RectangleShape rectangle;
rectangle.setSize(sf::Vector2f(20, 20));
rectangle.setOutlineColor(sf::Color::Red);
rectangle.setOutlineThickness(2);
rectangle.setPosition(100, 100);
window.setFramerateLimit(60);
int secondCounter = 0;
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
rectangle.rotate(10);
window.draw(rectangle);
window.display();
secondCounter++;
if(secondCounter>59)
{
std::cout << "Second elapsed." << std::endl;
secondCounter = 0;
sf::Thread thread(&tfunction);
thread.launch();
}
}
return 0;
}
This example shows an SFML window with a rectangle that rotates every 60 frames per second. Also, each every second, the program does a hard performance operation to calculate something big. I use a thread for this hard operation to avoid a delay or lag in the main process (the rotating rectangle).
But, as you can see if you run this little example, the main process is affected by the hard operation even when the process is launched in a parallel thread.
What am I doing wrong?