SFML community forums

Help => System => Topic started by: Acrobat on April 05, 2012, 12:40:00 pm

Title: Another sf::Thread topic about loading resources in background
Post by: Acrobat on April 05, 2012, 12:40:00 pm
Hello, i'm trying to load resources in background :
Code: [Select]
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

void LoadResources()
{
sf::Context context;
for (int i = 0; i < 100; i++)
{
sf::Texture * texture = new sf::Texture();
texture->loadFromFile("D:/2.png");
}
}

int main()
{
sf::RenderWindow m_window(sf::VideoMode(1024, 768, 32), "Test", sf::Style::Close);
sf::Text m_text("test");
sf::Clock clock;
while (m_window.isOpen())
{
m_text.setPosition(clock.getElapsedTime().asMilliseconds() / 100, 100  );
sf::Event event;
while(m_window.pollEvent(event))
{
if (event.type == sf::Event::Closed) {
m_window.close();
}
if (event.type == sf::Event::KeyPressed) {
// key down
if (event.key.code == sf::Keyboard::Space) {
sf::Thread thread(LoadResources);
thread.launch();
}
}
}
m_window.clear();
m_window.draw(m_text);
m_window.display();
}
return 0;
}

The problem is that the main thread stops rendering while the second thread is working.
Also tried to use mutex to sync (acording to example on wiki), no changes. Am i missing something ?
Win7 64
Title: Re: Another sf::Thread topic about loading resources in background
Post by: Laurent on April 05, 2012, 02:17:46 pm
Your thread instance is local to the "if" block, it is destroyed immediately and therefore it blocks the main thread (the destructor calls wait()).
Title: Re: Another sf::Thread topic about loading resources in background
Post by: Acrobat on April 05, 2012, 03:17:21 pm
thx, it works  :)