Make one qthread check the state of the other
I am doing an exercise qt console application on threading, here is the code:
Code:
// make two thread, one checking on the state of the other
//////////////////////////////////////
// main.cpp
#include "mytimer.h"
#include "mythread.h"
#include "checkthread.h"
#include <QCoreApplication>
#include <QString>
#include <QFile>
#include <QDebug>
int main(int argc, char *argv[])
{
MyThread mThread1;
mThread1.name = "thread 1";
mThread1.
start(QThread::HighestPriority);
CheckThread mCheck(&mThread1);
mCheck.start();
return a.exec();
}
///////////////////////////////////////
// mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QtCore>
{
public:
MyThread();
void run();
bool stop;
int sum;
};
#endif // MYTHREAD_H
//////////////////////////////////////
// mythread.cpp
#include "mythread.h"
MyThread::MyThread()
{
sum = 0;
}
void MyThread::run()
{
qDebug() << this->name << " running...";
for(int i=0; i<1000; i++) {
this->sum += i;
qDebug() << this->name << " counting " << sum;
this->sleep(1);
if(this->stop) {
break;
}
}
}
//////////////////////////////////////
// checkthread.h
#ifndef CHECKTHREAD_H
#define CHECKTHREAD_H
#include <QThread>
#include "mythread.h"
{
Q_OBJECT
public:
explicit CheckThread
(QObject *parent
= 0);
explicit CheckThread(MyThread *tocheck);
void run();
MyThread *tocheck_;
};
#endif // CHECKTHREAD_H
//////////////////////////////////////
// checkthread.cpp
#include "checkthread.h"
CheckThread
::CheckThread(QObject *parent
) : {
}
CheckThread::CheckThread(MyThread *tocheck) :
tocheck_(tocheck)
{
}
void CheckThread::run() {
while(true) {
this->sleep(1);
if(tocheck_->sum > 15) {
tocheck_->stop = true;
}
}
}
The expected behavior is that mThread1 shoud count to 15 and then stop,
but instead it is stuck at 0.
Interestingly (strangely, i mean), if I add the following code into the main.cpp file, then it runs
ok:
Code:
{
{
qDebug() << "Could not open file for writing";
return;
}
out << "hi world";
fh.flush();
fh.close();
}
{
{
qDebug() << "Could not open file for writing";
return;
}
qDebug() << mtext;
}
I am using qt 4.8 on a kubuntu 13.10 machine, and the ide is qt creator 3.0.1
Re: Make one qthread check the state of the other
You don't initialize MyThread::stop.
If my chance it is true, the thread will exit in the first iteration of its loop.
Also for a correct program you would need to protect the access of variables that are used by more than one thread. e.g. using QMutex
Cheers,
_
Re: Make one qthread check the state of the other
Yes, you are right!
But this does not explain why the Read and Write functions in main.cpp solves the problem. Very puzzling. :)
Re: Make one qthread check the state of the other
Quote:
Originally Posted by
kindlychung
But this does not explain why the Read and Write functions in main.cpp solves the problem. Very puzzling. :)
Coincidence.
Cheers,
_