让一个线程检查另一个线程的状态

Make one qthread check the state of the other

本文关键字:线程 检查 另一个 状态 一个      更新时间:2023-10-16

我正在做一个关于线程的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

问题是mythread.h中的成员var stop没有初始化

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