Monday, May 14, 2007

QThread

Thread not exiting

Yes, I assumed you did so.
Add the mCancelled member and replace the two "while" conditions with:

1. The first while:
Qt Code:
  1. while( !mCanceled )
2. The second while:
Qt Code:
  1. while( numMsgs && !mCancelled )
Declare mCancelled in the thread class as ( you can make it private ):
Qt Code:
  1. volatile bool mCancelled;
Also, add a new member function( public ):
Qt Code:
  1. void cancelThread();
  2. ...
  3. void CanRead::cancelThread()
  4. {
  5. mCancelled = true;
  6. }
All you have to do next is to call cancelThread instead of quit().
Note that it may take a little for the thread to stop, because it may be inside one of the loops when you set mCanceled to true. But this delay is acceptable, in my opinion, and you may not even notice it.

EDIT - Don;t forget to make mCancelled false in the constructor of the thread

No comments: