title: C++ terminate thread
body: <p>I know that this question has been asked and answered many times and I know that the <em>best</em> way to end a thread is to use flags and exit the thread function when it is requested. This is also what I am doing at the moment, but my problem is that the thread function runs for a very Long time, so sometimes I need to wait for several hours until the thread ends. My thread function looks something like this:</p>
  
  <pre><code>void threadfunction()
  {
      while(!exitRequested)
      {
          doSomeWork();
          object1.doSomeWork();
          object2.doSomeWork();
          while(somecondition)
          {
              object3.doSomeWork();
          }
          object4.doSomeWork();
      }
  }
  </code></pre>
  
  <p>This is just an example and in reality the code looks much more complex. But what I wanted to demonstrate is that I call several class methods which can take some hours to complete (per function).</p>
  
  <p>So what I'm doing at the moment is to check if exit was requested between the functions (e.g. between <code>object1.doSomeWork();</code> and <code>object2.doSomeWork();</code>) but as I said a function call can take up to several hours, so I need to check if exit was requested whithin those functions. In order to do this I need to pass the <code>exitRequested</code> flag to those functions, but in my opinion this doesn't look very nice and there could be a better solution for this.</p>
  
  <p>One solution I could think of is by throwing exceptions, to create something like this:</p>
  
  <pre><code>void threadfunction()
  {
      try {
          while(!exitRequested)
          {
              ...
          }
      } catch (const ExitRequestException &amp;e) {}
  }
  </code></pre>
  
  <p>But then the exception needs to be raised somehow. As far as I know I can't raise an exception in a thread from another thread, right?</p>
  
  <p>Do you have any better Solutions? Or do you think I really need to pass the <code>exitRequested</code> flag to all those functions and <em>pollute</em> my code?</p>