这是我目前的做法是如何的样子:如何实现多线程异步操作?
// 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