注:笔者只记录自己使用过的,粗浅了解,有其他想法,敬请讨论,其他线程相关待更新
QThread
通过 继承QThread
这是文件发送的类
#ifndef FILESEND_H
#define FILESEND_H
#include <QObject>
#include "QThread"
#include <QQueue>
#include <queue>
#include "tools.h"
using namespace std;
class fileSend : public QThread
{
Q_OBJECT
public:
explicit fileSend(QThread *parent = nullptr);
void closeThread();
protected:
virtual void run();//重点是重写这个函数,里面是一个独立的while(1)
signals:
public slots:
public:
private:
volatile bool isStop;
};
#endif // FILESEND_H
#include "filesend.h"
#include <QDebug>
#include <QMutex>
fileSend::fileSend(QThread *parent) : QThread(parent)
{
isStop = false;
}
void fileSend::closeThread()
{
isStop = true;
}
void fileSend::run()
{
uint8_t count = 0;
while (1)
{
if (isStop)
return;
/**TODO
这里面是我们要实现主要任务
*/
/*线程挂起时间*/
sleep(1);
}
}
界面调用
*.h中
fileSend *fileSendThread;
*.cpp中
/*第一步 线程初始化*/
fileSendThread = new fileSend;//fileSendThread 创建需要的类指针
/*开启一个线程*/
fileSendThread->start();
qDebug() << "主线程id:" << QThread::currentThreadId();//这会儿 run函数会周期性执行
当然线程还需要退出,以及资源回收,如果不写,可能会报警告意思是程序结束了,线程还在run
//在析构函数里面
fileSendThread->quit();
fileSendThread->wait();
fileSendThread = nullptr;
这里应该先调用closeThread(),笔者代码里没写,直接释放简单粗暴☹
直接使用QThread
*.h
CanAnaly *Canals;
QThread *CanAnalyThread;
*.cpp中
Canals = new CanAnaly;
CanAnalyThread = new QThread(this);
/* 把Canals转为线程 */
Canals->moveToThread(CanAnalyThread);
/* 线程启动 */
CanAnalyThread->start();
在我们需要线程的类中通过定时器来实现周期性调度
/* 自动收发定时器 */
QTimer *auto_receive_timer;
QTimer *auto_transmit_timer;
通过定时器周期性发送任务信号,来达到线程的目的
CanAnaly::CanAnaly(QObject *parent) : QObject(parent)
{
auto_receive_timer = new QTimer(this);
auto_transmit_timer = new QTimer(this);
/* 收发定时器 */
connect(auto_receive_timer, SIGNAL(timeout()), this, SLOT(auto_receive()));
connect(auto_transmit_timer, SIGNAL(timeout()), this, SLOT(auto_transmit()));
/*开启定时器*/
// connect(this,&CanAnaly::receive_msg_signals,this,&CanAnaly::auto_receive_timer_ctrl);
auto_receive_timer->start(1);
}