Search code examples
c++multithreadingsfmlfreeze

c++ - sf::Thread freezes main thread when run in the while(window.isOpen()) loop


I'm trying to launch an sf::Thread (because default C++ threads are hideously bad, as they crash constantly when executing them in the while(window.isOpen()) loop) in my project, which displays a text in a box (This is suposed to be the text modification thread).

The issue arises when executing the thread in the while(window.isOpen()) loop, where it freezes the main thread until it has finished execution. However, executing it before won't freeze the program and will run independently.

The thread is sf::Thread t(std::bind(Display, std::ref(*messageBoxText), "some random things", 2000));, where messageBoxText is a sf::Text, "some random things" is a std::string and 2000 is a int which states the millisecond delay.

The Display function is:

static void Display(sf::Text &text, std::string textToPut, int msDelay = 10000){
            conts int TEXT_NEWLINE_CONSTANT = 52; 
            int size = textToPut.size();

            vector<string> strings;

            const int numberOfNewlines{(size / TEXT_NEWLINE_CONSTANT) + 1};


            for(int i{0}; i < numberOfNewlines; i++){
                string tmp {""};
                for(int j{TEXT_NEWLINE_CONSTANT * i}; j < TEXT_NEWLINE_CONSTANT * (i + 1) && j < size; j++){
                    tmp += textToPut[j];
                }
                strings.push_back(tmp);
            }
    
            for(int i{0}; i < numberOfNewlines; i++){
                if(i == 0){
                    text.setString(strings[i]);
                } else if (i > 0){
                    string tmp = strings[i - 1] + "\n" + strings[i];
                    text.setString(tmp);
                }
                sf::sleep(sf::milliseconds(msDelay));
            }

            sf::sleep(sf::milliseconds(msDelay * 2)); 
        }

Solution

  • Suggest you use std::thread and detach the thread

    Thank you for your suggestion. Changing

    sf::Thread t(std::bind(Display, std::ref(*messageBoxText), "some random things", 2000));
    t.launch();
    

    to

    std::thread t(std::bind(Display, std::ref(*messageBoxText), "some random things", 2000));
    t.detach();
    

    makes it work. Thanks!