Benjamin
Benjamin

Reputation: 1183

Interrupt thread after amount of time, without blocking while waiting

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?

Upvotes: 1

Views: 1145

Answers (2)

Paolo Brandoli
Paolo Brandoli

Reputation: 4728

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.

Upvotes: 0

Nikko
Nikko

Reputation: 4252

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.

Upvotes: 1

Related Questions