在通信中,往往会遇到这样的情况
当接入N个子结点,每个子结点向它的父结点发数据,父节点来并发处理总子结点汇集的数据。
对于上述情况,我们经常设计成多线程来并发接收数据,将数据接收后排队存入一个全局变量,再单独开辟一个线程从这个全局变量读取第一个数据,处理完则移除第一个数据。Qt中的链表直接提供了一个takeFirst函数,用while循环读取,在读取的时候加锁,这样的话就不会冲突了。
在这里我们设计了一个定时器来模拟子结点产生的数据,开辟一个单独的线程来读取数据。
关键代码:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "qtimer.h"
#include "thread.h"
#include "app.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
QTimer *timer;
Thread *thread;
private slots:
void writeOne();
void readOne(QString txt);
void on_btnTimer_clicked();
void on_btnThread_clicked();
void on_btnAppend_clicked();
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include<QTimer>
#include "qdatetime.h"
#define _TIME_ qPrintable (QTime::currentTime().toString("now : hh:mm:ss:zzzz"))
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("并发数据处理的简单举例");
timer = new QTimer(this);
timer->setInterval(50);
connect(timer,SIGNAL(timeout()),this,SLOT(writeOne()));
thread = new Thread;
connect(thread,SIGNAL(readOne(QString)),this,SLOT(readOne(QString)));
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_btnTimer_clicked()
{
if (ui->btnTimer->text()=="start timer"){
timer->start();
ui->btnTimer->setText("stop timer");
ui->txtOut->append("start timer ok");
}else{
timer->stop();
ui->btnTimer->setText("start timer");
ui->txtOut->append("stop timer ok");
}
}
void MainWindow::on_btnThread_clicked()
{
if (ui->btnThread->text()=="start thread"){
thread->start();
ui->btnThread->setText("stop thread");
ui->txtOut->append("start thread ok");
}else{
thread->stop();
ui->btnThread->setText("start thread");
ui->txtOut->append("stop thread ok");
}
}
void MainWindow::on_btnAppend_clicked()
{
App::list.append(ui->lineEdit->text());
}
void MainWindow::writeOne()
{
App::list.append(_TIME_);
}
void MainWindow::readOne(QString txt)
{
ui->txtOut->append(txt);
}
#ifndef THREAD_H
#define THREAD_H
#include "qthread.h"
#include "qmutex.h"
#include "app.h"
class Thread:public QThread
{
Q_OBJECT
public:
Thread();
~Thread();
void stop();
protected:
void run();
private:
QMutex mutex;
volatile bool stopped;
signals:
void readOne(QString txt);
};
#endif // THREAD_H
#include "thread.h"
//#include "app.h"
extern QList<QString> list;
Thread::Thread()
{
stopped = false;
}
Thread::~Thread()
{
}
void Thread::stop()
{
stopped = true;
}
void Thread::run()
{
while(!stopped){
mutex.lock();
if(App::list.count()>0)
{
QString txt = App::list.takeFirst();
emit readOne(txt);
}
mutex.unlock();
msleep(1);
}
stopped = false;
}
#ifndef APP_H
#define APP_H
#include<QList>
class App{
public:
static QList<QString> list;
};
QList<QString> App::list = QList<QString>();
#endif // APP_H
参考文章:
https://blog.csdn.net/xu1129005165/article/details/81702924