【问题标题】:c++ - sf::Thread freezes main thread when run in the while(window.isOpen()) loopc++ - sf::Thread 在 while(window.isOpen()) 循环中运行时冻结主线程
【发布时间】:2022-01-02 07:47:59
【问题描述】:

我正在尝试在我的项目中启动一个 sf::Thread(因为默认的 C++ 线程非常糟糕,因为它们在while(window.isOpen()) 循环中执行它们时会不断崩溃),它会在一个框中显示一个文本(这个应该是文本修改线程)。

while(window.isOpen()) 循环中执行线程时会出现问题,它会冻结主线程直到它完成执行。但是,之前执行它不会冻结程序并且会独立运行。

线程是sf::Thread t(std::bind(Display, std::ref(*messageBoxText), "some random things", 2000));,其中messageBoxText 是sf::Text,“一些随机事物”是std::string,2000 是int,表示毫秒延迟。

显示功能是:

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)); 
        }

【问题讨论】:

  • "...它冻结主线程直到它完成执行..." - _This destructor [of sf::Thread] 调用 sf::Thread::wait() , 从而使内部线程在其sf::Thread 实例被销毁后无法生存” - 参见 - sfml-dev.org/documentation/2.5.1/… 建议您使用std::thread 并分离线程。
  • 另外 - "...因为默认的 C++ 线程非常糟糕..." - 请解释一下 std::thread 是一个非常薄的原生操作系统线程的包装器。跨度>

标签: c++ multithreading sfml freeze


【解决方案1】:

建议你使用 std::thread 并分离线程

感谢您的建议。改变

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

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

让它工作。谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-14
    • 2015-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 1970-01-01
    • 2017-10-20
    相关资源
    最近更新 更多