Hi, I'm learning QMutex class and I have some problems. This is the code I have so far:

test.h
Qt Code:
  1. #ifndef TEST_H
  2. #define TEST_H
  3.  
  4. #include <QtGui>
  5. #include <iostream>
  6. #include <QThread>
  7.  
  8. class Thread : public QThread {
  9. Q_OBJECT
  10.  
  11. public:
  12. Thread(const QString &mes);
  13. void setMessage1(const QString &message);
  14. void setMessage2(const QString &message);
  15. void printMessage(const QString &t);
  16. void stop();
  17.  
  18. protected:
  19. void run();
  20.  
  21. private:
  22. QString message_str;
  23. QMutex mutex;
  24. };
  25.  
  26.  
  27.  
  28. class ThreadDialog : public QDialog {
  29. Q_OBJECT
  30.  
  31. public:
  32. ThreadDialog(QWidget *parent = 0);
  33.  
  34. };
  35.  
  36.  
  37. #endif
To copy to clipboard, switch view to plain text mode 


test.cpp
Qt Code:
  1. #ifndef TEST_CPP
  2. #define TEST_CPP
  3. #include "test.h"
  4.  
  5. Thread::Thread(const QString &mes) {
  6. message_str = mes;
  7. }
  8.  
  9. void Thread::run() {
  10. //mutex.lock();
  11. //QThread::msleep(1000);
  12. //printMessage("START");
  13. //mutex.unlock();
  14. }
  15.  
  16. void Thread::stop() {
  17. //mutex.lock();
  18. //printMessage("STOP");
  19. //mutex.unlock();
  20. }
  21.  
  22. void Thread::setMessage1(const QString &message) {
  23. //mutex.lock();
  24. printMessage("START");
  25. message_str = message;
  26. QThread::msleep(2000);
  27. printMessage("STOP");
  28. //mutex.unlock();
  29. }
  30.  
  31. void Thread::setMessage2(const QString &message) {
  32. //mutex.lock();
  33. printMessage("START");
  34. message_str = message;
  35. QThread::msleep(2000);
  36. printMessage("STOP");
  37. //mutex.unlock();
  38. }
  39.  
  40. void Thread::printMessage(const QString &t) {
  41. qDebug() << t << ": " << message_str << flush;
  42. }
  43.  
  44.  
  45. ThreadDialog::ThreadDialog(QWidget *parent) : QDialog(parent) {
  46. Thread threadA("A");
  47. Thread threadB("B");
  48. threadA.start();
  49. threadB.start();
  50. threadA.setMessage1("A");
  51. threadB.setMessage2("B");
  52.  
  53.  
  54. //threadB.stop();
  55. //threadA.stop();
  56. }
  57.  
  58.  
  59.  
  60. #endif
To copy to clipboard, switch view to plain text mode 


main.cpp
Qt Code:
  1. #include <QApplication>
  2. #include "test.h"
  3.  
  4. int main(int argc, char **argv) {
  5. QApplication app(argc, argv);
  6. ThreadDialog *dialog = new ThreadDialog;
  7. //dialog->show();
  8. return app.exec();
  9. }
To copy to clipboard, switch view to plain text mode 

I wish to change the program so that both threads would be started first and then stopped...but when used with QMutex the output would be first one is stared&stoped and then the second started&stopped...now the second scenario already happens, but it shouldn't, why is that?