SFML community forums

Help => System => Topic started by: Kookies on April 29, 2021, 05:07:53 pm

Title: Threads are Freezing my Window
Post by: Kookies on April 29, 2021, 05:07:53 pm
This is a function I'm using to spawn enemies, and I'm using sf::sleep to add a delay.
void spawn()
{
        sleep(seconds(2));
        if (count1 % 20 && count1 != 0)
        {
                enemies.push_back(Enemy(true, 500.0, 25.0, 50.0, 50.0, Color::Red));
        }
        else
        {
                enemies.push_back(Enemy(false, 100.0, 15.0, 50.0, 50.0, Color::White));
        }
        count1++;
}
I launch the thread from here:
Thread spawning(&spawn);
        spawning.launch();
But for some reason, the sleep in the thread affects my main loop and causes it to update every two seconds.
Title: Re: Threads are Freezing my Window
Post by: Laurent on April 30, 2021, 08:04:56 am
If the Thread object is created within the main loop, it is destroyed in it as well, and the destructor of class Thread blocks until the thread's function has returned.
Title: Re: Threads are Freezing my Window
Post by: Kookies on April 30, 2021, 04:11:31 pm
So where should I create it?
Title: Re: Threads are Freezing my Window
Post by: Laurent on April 30, 2021, 04:28:40 pm
Outside the game loop. But then you'll have to change the logic of the spawn() function.

But... it makes no sense to run a thread just to make it wait. To do nothing during 2 seconds, you definitely don't need a thread. Just use a sf::Timer and call the spawn() function whenever it reaches 2 seconds.