PDA

View Full Version : QThread + QMutex example



eleanor
13th February 2010, 15:39
Hi, I'm learning QMutex class and I have some problems. This is the code I have so far:

test.h


#ifndef TEST_H
#define TEST_H

#include <QtGui>
#include <iostream>
#include <QThread>

class Thread : public QThread {
Q_OBJECT

public:
Thread(const QString &mes);
void setMessage1(const QString &message);
void setMessage2(const QString &message);
void printMessage(const QString &t);
void stop();

protected:
void run();

private:
QString message_str;
QMutex mutex;
};



class ThreadDialog : public QDialog {
Q_OBJECT

public:
ThreadDialog(QWidget *parent = 0);

};


#endif




test.cpp


#ifndef TEST_CPP
#define TEST_CPP
#include "test.h"

Thread::Thread(const QString &mes) {
message_str = mes;
}

void Thread::run() {
//mutex.lock();
//QThread::msleep(1000);
//printMessage("START");
//mutex.unlock();
}

void Thread::stop() {
//mutex.lock();
//printMessage("STOP");
//mutex.unlock();
}

void Thread::setMessage1(const QString &message) {
//mutex.lock();
printMessage("START");
message_str = message;
QThread::msleep(2000);
printMessage("STOP");
//mutex.unlock();
}

void Thread::setMessage2(const QString &message) {
//mutex.lock();
printMessage("START");
message_str = message;
QThread::msleep(2000);
printMessage("STOP");
//mutex.unlock();
}

void Thread::printMessage(const QString &t) {
qDebug() << t << ": " << message_str << flush;
}


ThreadDialog::ThreadDialog(QWidget *parent) : QDialog(parent) {
Thread threadA("A");
Thread threadB("B");
threadA.start();
threadB.start();
threadA.setMessage1("A");
threadB.setMessage2("B");


//threadB.stop();
//threadA.stop();
}



#endif




main.cpp


#include <QApplication>
#include "test.h"

int main(int argc, char **argv) {
QApplication app(argc, argv);
ThreadDialog *dialog = new ThreadDialog;
//dialog->show();
return app.exec();
}



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?

franz
13th February 2010, 16:54
The thread stops immediately because the run() function is empty. You don't see any output from the actual running of the thread in this implementation.
The setMessage*() functions are called sequentially inside the same thread (the main thread), therefore they are executed sequentially.

psih128
13th February 2010, 17:48
To add to franz comment:
Thread objects are allocated on the stack, so they are destroyed as soon as the dialog constructor returns. Allocate them in the following manner:


Thread *threadA = new Thread("A");

I dont quite understand what is the desired behavior, but if you want to learn how to signal threads from your main thread, then you should use QMutex objects along with QWaitCondition. Read the documentation and examples more about these classes.