QThread学习

工作需要,前段时间要写TCP连接的模块,因为连接本身可能是一个耗时的操作,而且要实现自动重连功能,所以必须要用到多线程,因此有机会学习QThread,现将体会成文。

首先是QThread::exec(),这个函数将进入当前线程的事件循环(网上很多文章都写成时间循环),调用这个函数后将会阻塞线程,这时线程中的事件传递才有效,信号与槽的连接才有效,此时信号发射后槽函数才会被调用。当执行了线程的quit()或exit()函数时exec()函数才返回。

看程序

//mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
class QTimer ;
class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = 0);
protected:
    void run();
public slots:
    void slotFunc();
private:
    QTimer *timer;    
};
#endif // MYTHREAD_H

//mythread.cpp
#include "mythread.h"
#include <QtDebug>
#include <QTimer>
MyThread::MyThread(QObject *parent) :
    QThread(parent)
{
}
void MyThread::run()
{
    timer = new QTimer;
    timer->setSingleShot(true);
    timer->start(5000);
	qDebug() << timer << QThread::currentThreadId();
    connect(timer, SIGNAL(timeout()), this, SLOT(slotFunc()));
    exec();
    qDebug() << "********************";
}
void MyThread::slotFunc()
{
    qDebug() << timer << QThread::currentThreadId();
    qDebug() << "#################";
}

//main.cpp
#include <QApplication>
#include "mythread.h"
int main(int argc, c
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值