0

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.

Yana D. Nugraha
  • 5,069
  • 10
  • 45
  • 59
  • This piece of code that you presented should work. Could you somehow specify "unhandled exceptions"? – MeloMCR Sep 05 '12 at 20:12
  • I'm using SFML2 for rendering stuffs and the exception comes from SFML's MutexImpl.cpp. I'm afraid it'll be too specific for the question if the details comes from another library. – Yana D. Nugraha Sep 05 '12 at 20:51

2 Answers2

1

There are so many ways to do this its hard to pin down. With Windows you'll often kick the thread off based on a GUI action, and the results and/or progress are posted back to the GUI via the message pump loop. You'll declare or register custom window messages, and have the various reporting positions of your worker thread post them to the main window handle or child window handle setup to monitor the async progress.

There are many, many ways to do this. The above is only one description, but for moderate tasks it is one i find generally solves the problem. That being the case, you're right on with the code you have shown here. you're setting directly and bypassing the message loop (not really, but as far as you need be concerned you are), so this should work.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141
0

If you can use either of Boost or C++11, have a shot at boost/std::future and async

Joel Falcou
  • 6,247
  • 1
  • 17
  • 34