Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Threads are Freezing my Window  (Read 13238 times)

0 Members and 1 Guest are viewing this topic.

Kookies

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Threads are Freezing my Window
« 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.

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Threads are Freezing my Window
« Reply #1 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.
Laurent Gomila - SFML developer

Kookies

  • Newbie
  • *
  • Posts: 2
    • View Profile
    • Email
Re: Threads are Freezing my Window
« Reply #2 on: April 30, 2021, 04:11:31 pm »
So where should I create it?

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32498
    • View Profile
    • SFML's website
    • Email
Re: Threads are Freezing my Window
« Reply #3 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.
Laurent Gomila - SFML developer

 

anything