![](/img/trans.png)
[英]C++ SFML Draw objects outside of while (window.isOpen()) loop
[英]c++ - sf::Thread freezes main thread when run in the while(window.isOpen()) loop
我正在嘗試在我的項目中啟動一個 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
。
顯示 function 是:
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));
}
建議您使用 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();
讓它工作。 謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.