1

I'd like to start a thread in the background and want to stop it after a certain amount of time if it not finishes. Main Problem is, while waiting for the thread to finish or a timer to reach a deadline, the program should not block. Its important to guarentee that.

I tried this example, but while waiting for timed_join, it blocks. I have to announce a warning that there is some calculation in progress.

void CallbackReceived() {
  boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(500);
  boost::thread thrd(&Foo);

  if (thrd.timed_join(timeout)) {
    //finished
  } else {
    //Not finished;
  }
}

Do you have any suggestions?

Community
  • 1
  • 1
Benjamin
  • 1,143
  • 1
  • 14
  • 29
  • 3
    Off the top of my head, 'announce the warning, before waiting for completion', 'have another background thread be responsbile for monitoring the first', 'change the first thread so that it is aware of time constraints and can abort itself..' – forsvarir Sep 20 '11 at 08:06
  • 1
    Start another thread that will call `timed_join`. – n. m. could be an AI Sep 20 '11 at 08:07
  • 1
    @forsvarir i'd make that pretty much an answer. – RedX Sep 20 '11 at 08:15

2 Answers2

1

You can start a thread that will start your thread and wait for the timed_join.

main
|
|---thread
|      |
|      |-----thread
|               |
|               |
|               |
|     join<------     
|
|

But if you just want a warning, put it before starting the thread. If it is a graphical application and you still want to handle events, you have to have your main thread available as shown above.

Nikko
  • 4,182
  • 1
  • 26
  • 44
0

The thread that must be stopped could exit by itself after a certain amount of time.

For instance, if it executes all the work in a loop, it could periodically check (e.g. every 10 iterations of the loop) if the maximum amount of time has passed and exit in the case the time has passed.

Every now and then the main thread could check for thread that finished the job (or terminated prematurely) and remove them.

Paolo Brandoli
  • 4,681
  • 26
  • 38