Search code examples
c++multithreadingboost-thread

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?


Solution

  • 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.