让一个线程检查另一个线程的状态
Make one qthread check the state of the other
我正在做一个关于线程的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函数可以解决这个问题。很令人费解。
相关文章:
- 如何检查线程是否锁定
- 检查分离的线程是否还活着?
- 确保静态布尔检查的线程安全
- 检查Linux功能以设置线程优先级
- Valgrind 检查简单多线程 C++11 得到 SIG11 错误
- c++线程的安全性和时间效率:为什么有互斥检查的线程有时比没有它的线程工作得更快
- 检查线程是否在 c++11 中完成
- 检查线程中的WM_LBUTTONDOWN
- NULL指针检查线程安全
- C++ 互斥 - 检查另一个线程是否正在等待
- mutex::lock() 检查一次解锁状态是否已经被另一个线程锁定?
- 这是否可以兑换线程安全的双重检查锁定模式
- 期货是检查单个线程完成情况的安全方法吗
- 简单的线程计时器,请检查是否正常
- 提升线程死锁,任何人都可以检查原因
- 提升线程 检查当前线程是否等于另一个本机句柄
- C++如何检查文件是否在使用-多线程多进程系统
- 线程安全惰性初始化:静态vs std::call_once vs双重检查锁定
- 如何检查std::线程是否仍在运行
- 让一个线程检查另一个线程的状态