title: How to implement cancel method for a C++ library
body: <p>I'm developing a C++ library used for OCR purpose. The problem coming when I need to add the feature cancel/stop its work immediately (&lt;= 0.4 seconds) after user send cancel signal (just a boolean function pointer), without any memory leaking error.
  Now, I choose the solution to place a lot of checkpoint after each function that consume around 1% performance by profiling. Then I will throw an exception and catch that exception in the highest caller and use smart pointer to prevent my library from memory leaking too. It take 20 checkpoint to do that purpose because alot of them are inside a loop.
  But I see that this solution is bad, because it can't ensure the target 0.4 seconds in most case. And the effort to prevent memory leak is very high too. Also, it's hard to maintain this logic when the library is continued to develope.</p>
  
  <p>Can you propose for me an better solution to overcome this issue?
  Thanks you very much!</p>
  
  <p>My case is demo simply as bellow:</p>
  
  <pre class="lang-cpp prettyprint-override"><code>#include "OCRSetting.h"
  #include "OCRDocument.h"
  
  bool is_cancel(false);
  
  bool IsCancel() {
    return is_cancel;
  }
  
  int main() {
    // OCR setting
    OCRSetting setting;
  
    // Create document
    OCRDocument document(image_path, setting);
    document.SetCancelMethod(IsCancel);
  
    // This is a action take a lot of time, when this action happen, the controller
    // thread can change the result of IsCancel to true and the requirement is that
    // methid Export must return immedidately with response time smaller than 0.4 seconds
    // Target CPU frequency is 1.33 GHz
    int status = document.Export();
  
    return status;
  }
  </code></pre>