我写的一个线程,做用是调用别外一个人写的读取后台数据的接口!因为数据有时候会比较大,老板要求有个交互界面,可是读数据的部分不是我写的,进度条没法弄,SO,做了个QMESSAGEBOX写了个读取中,放在那,为了加快读的速度,用线程来做的,确实快了点,界面也不会在读的时候死掉,可是经常或者偶尔读完了反回信号的时候死在那个QMESSAGEBOX界面上(不同的电脑几率不同,貌似老CPU几率较大).
我是这样设计的 用户操作读取->给出读取中的QMESSAGEBOX->调用读的线程->读取成功->返回数据->关掉读取中的QMESSAGEBOX->显示数据
线程的代码如下:
class ThreadReadreport : public QThread //用户定义的线程类
{
Q_OBJECT
public:
ThreadReadreport(RPT_FILE *rptfile,bool *read,QObject *parent = 0);
protected:
void run();
private:
RPT_FILE *rptfile;
QMutex mutex;
bool *read;
QWaitCondition condition;
signals:
void readdone(bool);
};
/******************************************************************************
*
* 报告读取的线程
*
* IN:
* rptfile,要读的报告指针
* read,判断是否读取成功的变量
*
*/
ThreadReadreport::ThreadReadreport(RPT_FILE *rptfile,bool *read,QObject *parent): QThread(parent)
{
mutex.lock();
this->rptfile = rptfile;
this->read = read;
mutex.unlock();
}
/******************************************************************************
*
* 报告读取线程的执行函数
*
*
*/
void ThreadReadreport::run()
{
mutex.lock();
if(reportread(*rptfile))
{
*read = true;
string loginfor;
loginfor = "报告(" + rptfile->name + ")读取";
if(ERR == WriteLog(APP_REPORT_MGMT,OP_READ,USR_OP_STATE_FINISH,loginfor))
{
}
}
else
*read = false;
mutex.unlock();
}
调用部分的函数:
/******************************************************************************
*
* 打开读报告线程
* IN:
* rptname,报告名
* ALL:
* test,QMessageBox;
*/
void Report_MainWindow::rptopen(QString rptname)
{
test= new QMessageBox(this);
test->setWindowTitle("读取报告");
test->setIcon(QMessageBox::Information);
test->setText("正在载入报告,这段时间可能较长,请稍候....");
test->setStandardButtons(QMessageBox::NoButton);
test->show();
/*读取当前报告*/
currentrpt.name = rptname.toLocal8Bit().data();
QMutex mutex;
ThreadReadreport *readrpt = new ThreadReadreport(¤trpt,&rptrs);
readrpt->start();
connect(readrpt,SIGNAL(finished()),this,SLOT(rptbuild()));
}
/******************************************************************************
*
* 读报告线程完毕打开报告
*
* ALL:
* test,QMessageBox;
*/
void Report_MainWindow::rptbuild()
{
test->accept();
if(rptrs)
{
detailsNo_show = -1;
/*建立报告漏洞列表*/
createvullist(currentrpt.report.reports[0],vulshowconfig);
/*报告显示*/
QString sum = Summary(currentrpt.report.reports[0],0);
sum_textEdit->setHtml(sum);
/*报告显示一系列控件控制*/
Report_MainWindow::setWindowTitle(tr("%1 - %2").arg("报告").arg(currentrpt.name.c_str()));
sum_groupBox->setHidden(true);
col_groupBox->setHidden(true);
sum_textEdit->setHidden(false);
menucontrol(true);
}
else
QMessageBox::critical(this,"错误信息","报告读取错误!");
}
界面偶尔会死在那个test的QMessageBox上不动,几率因机而异,实在是想破头也不知道怎么回事!谢谢达人们了