Qt线程在sleep时能否处理信号

问题

写这个demo的意图是想验证Qt的线程在sleep的情况下能否正常处理其他线程发过来的信号。

验证代码

例子很简单。线程sleep 10分钟,点击主窗口按钮,发送命令,看线程是否能够响应。代码如下:

线程代码:

threadtest.h

#ifndef THREADTEST_H

#define THREADTEST_H

 

#include <QThread>

 

class threadtest : public QThread

{

    Q_OBJECT

public:

    explicit threadtest(QObject*parent = 0);

protected:

    void run();

private:

    bool m_run;

public slots:

    void on_button_clicked();

   

};

 

#endif // THREADTEST_H

 

threadtest.cpp

#include "threadtest.h"

#include <QtCore/QDebug>

 

threadtest::threadtest(QObject *parent) : m_run(false),

    QThread(parent)

{

}

 

void threadtest::run()

{

    m_run = true;

    while(m_run)

    {

        qDebug()<<"wait";

        sleep(600);

    }

}

 

void threadtest::on_button_clicked()

{

    qDebug()<<"buttonclicked";

}

 

界面代码

mainwindow.h

#ifndef MAINWINDOW_H

#define MAINWINDOW_H

 

#include <QMainWindow>

#include <QtGui/QPushButton>

 

namespace Ui {

class MainWindow;

}

 

class MainWindow : public QMainWindow

{

    Q_OBJECT

   

public:

    explicit MainWindow(QWidget*parent = 0);

    ~MainWindow();

   

private:

    Ui::MainWindow *ui;

    QPushButton *m_btn;

};

 

#endif // MAINWINDOW_H

 

mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "threadtest.h"
 
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_btn = new QPushButton(tr("button clicked"),this);
    m_btn->setGeometry(20,20,100,25);
 
    threadtest *t = new threadtest();
    connect(m_btn,SIGNAL(clicked()),t,SLOT(on_button_clicked()));
    t->start();
 
}
 
MainWindow::~MainWindow()
{
    delete ui;
}

 

main.cpp

#include "mainwindow.h"

#include <QApplication>

 

int main(int argc, char *argv[])

{

    QApplication a(argc, argv);

    MainWindow w;

    w.show();

   

    return a.exec();

}

 

运行结果

QDateTime("周五六月 14 09:45:39 2013") wait

QDateTime("周五六月 14 09:45:45 2013") button clicked

QDateTime("周五六月 14 09:45:46 2013") button clicked

QDateTime("周五六月 14 09:45:46 2013") button clicked

QDateTime("周五六月 14 09:45:47 2013") button clicked

QDateTime("周五六月 14 09:45:47 2013") button clicked

QDateTime("周五 六月 14 09:45:482013") button clicked

 

结论

Qt线程在sleep的情况下依然可以接收处理来自其他线程的信号

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值