以下是我目前的方法:
// 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部分。
答案 0 :(得分:1)
有很多方法可以做到这一点很难确定。使用Windows,您通常会根据GUI操作启动线程,并通过消息泵循环将结果和/或进度发回GUI。您将声明或注册自定义窗口消息,并将工作线程的各种报告位置发布到主窗口句柄或子窗口句柄设置以监视异步进度。
有许多方法可以做到这一点。以上只是一个描述,但对于中等任务,我发现通常可以解决问题。既然如此,您就可以使用此处显示的代码。你是直接设置并绕过消息循环(不是真的,但就你需要担心的那样),所以这应该有效。
答案 1 :(得分:0)
如果你可以使用Boost或C ++ 11中的任何一个,那就试试boost / std :: future和async