让一个qthread检查另一个的状态

时间:2014-05-16 12:40:37

标签: c++ multithreading qt

我正在线程上练习qt控制台应用程序,这里是代码:

// 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[])
{
    QCoreApplication a(argc, 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>

class MyThread : public QThread
{
public:
    MyThread();
    void run();
    QString name;
    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"

class CheckThread : public QThread
{
    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) :
    QThread(parent)
{
}

CheckThread::CheckThread(MyThread *tocheck) :
    tocheck_(tocheck)
{
}

void CheckThread::run() {
    while(true) {
        this->sleep(1);
        if(tocheck_->sum > 15) {
            tocheck_->stop = true;
        }
    }
}

预期的行为是mThread1应该计数到15然后停止, 但它被卡在了0。

有趣的是,如果我将以下代码添加到main.cpp文件中,那么它就会运行 确定:

void Write(QString Filename)
{
    QFile fh(Filename);
    if(!fh.open(QFile::WriteOnly | QFile::Text))
    {
        qDebug() << "Could not open file for writing";
        return;
    }
    QTextStream out(&fh);
    out << "hi world";
    fh.flush();
    fh.close();
}

void Read(QString Filename)
{
    QFile fh(Filename);
    if(!fh.open(QFile::ReadOnly | QFile::Text))
    {
        qDebug() << "Could not open file for writing";
        return;
    }
    QTextStream in(&fh);
    QString mtext = in.readAll();
    qDebug() << mtext;
}

我在kubuntu 13.10机器上使用qt 4.8,而ide是qt creator 3.0.1

1 个答案:

答案 0 :(得分:0)

问题是mythread.h中的成员var stop未初始化。

但这并不能解释为什么main.cpp中的Read和Write函数解决了这个问题。非常令人费解。