How to implement a multi-threaded asynchronous operation?
- by drowneath
Here's how my current approach looks like:
// 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;
}
}
But I'm afraid this is far from safe since I keep getting unhandled exception at the end of the program execution.
I basically want to separate a heavy task into another thread without blocking the GUI part.