title: How to stop a running thread safely on user request?
body: <p>I'm in a scenario when I have to terminate a thread while the thread is running according to user action on GUI. I'm using Qt 4.5.2 on Windows. One way to do that is the following:</p>
  
  <pre><code>class MyThread : public QThread
  {
      QMutex mutex;
      bool stop;
  
      public:
          MyThread() : stop(false) {}
  
          void requestStop()
          {
              QMutexLocker(&amp;mutex);
              stop = true;
          }
  
          void run()
          {
              while(counter1--)
              {
                  QMutexLocker(&amp;mutex);
                  if (stop) return;
  
                  while(counter2--)
                  {
                  }
              }
          }
  };
  </code></pre>
  
  <p>Please note that the above code is minimal. The run function can take upto 20 seconds before finish so I want to avoid locking and unlocking the <code>mutex</code> variable in the loop. Is there any other way faster than this method.</p>
  
  <p>Thanks in advance.</p>