开发者

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜