這是我目前的做法是如何的樣子:如何實現多線程異步操作?
// Somewhere in a UI class
// Called when a button called "Start" clicked
MyWindow::OnStartClicked(Event &sender)
{
_thread = new boost::thread(boost::bind(&MyWindow::WorkToDo, this));
}
MyWindow::WorkToDo()
{
for(int i = 1; i < 10000000; i++)
{
int percentage = (int)((float)i/100000000.f);
_progressBar->SetValue(percentage);
_statusText->SetText("Working... %d%%", percentage);
printf("Pretend to do something useful...\n");
}
}
// Called on every frame
MyWindow::OnUpdate()
{
if(_thread != 0 && _thread->timed_join(boost::posix_time::seconds(0))
{
_progressBar->SetValue(100);
_statusText->SetText("Completed!");
delete _thread;
_thread = 0;
}
}
但是這恐怕是遠遠安全的,因爲我一直在程序執行結束時獲得未處理的異常。
我基本上想把一個繁重的任務分成另一個線程而不阻塞GUI部分。
這段代碼,您提出應該工作。你能不知怎的指定「未處理的異常」? – MeloMCR
我使用SFML2渲染東西,異常來自SFML的MutexImpl.cpp。如果細節來自另一個圖書館,我擔心這個問題會過於具體。 – drowneath