c++ - Qt GUI 应用程序在与 gui 交互时停止实时进程

标签 c++ multithreading qt user-interface

我有一个 Qt GUI 应用程序,它正在做一些重要的实时工作,无论如何都不能被打断(通过 LAN 转发一些传入的串行流量)。目前,当没有与 GUI 的交互时,应用程序运行完美,但是一旦您单击按钮或拖动表单,似乎在处理单击时转发已停止。转发是在 QTimer 循环中完成的,我已经把它放在与 GUI 线程不同的线程上,但结果没有变化。 以下是部分代码:

class MainWindow : public QMainWindow
{
    QSerialPort serialReceiver; // This is the serial object
    QTcpSocket *clientConnection;
}

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    // Some Initializations ...

    QThread* timerthread = new QThread(this); // This is the thread that is supposed to do the forwarding
    QTimer *timer = new QTimer(0);
    timer->setInterval(25);
    timer->moveToThread(timerthread);

    connect(timer ,SIGNAL(timeout()),this,SLOT(readserialData())); // Run readserialData() each 25ms
    timer->connect(timerthread, SIGNAL(started()), SLOT(start()));
    timerthread->start();
}


void MainWindow::readserialData()
{
    if(serialReceiver.isOpen() )
    {
        qint64 available = serialReceiver.bytesAvailable();
        if(available > 0)  // Read the serial if any data is available
        {    
            QByteArray serialReceivedData = serialReceiver.readAll(); // This line would not be executed when there is an interaction with the GUI
            if(isClientConnet)
            {
                int writedataNum = clientConnection->write(serialReceivedData);
            }
        }
    }
}

正如我之前所说,这段代码在空闲情况下运行良好,没有任何数据丢失。我做错了什么吗?

最佳答案

在另一个线程中运行重要的实时工作是个好主意。 GUI 线程或主线程应该进行绘图,另一个应该进行处理。

Qt 关于 GUI 线程的文档说:

GUI Thread and Worker Thread As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary threads. A secondary thread is commonly referred to as a "worker thread" because it is used to offload processing work from the main thread.

以及何时使用多线程

Using Threads There are basically two use cases for threads: Make processing faster by making use of multicore processors. Keep the GUI thread or other time critical threads responsive by offloading long lasting processing or blocking calls to other threads.

在您的情况下,在单独的线程中运行实时处理将解决 UI 滞后问题,也将解决实时性问题。

我建议您阅读 Qt 文档中的线程基础知识。

Threading basics

关于c++ - Qt GUI 应用程序在与 gui 交互时停止实时进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41409098/

相关文章:

c++ - 将 GPIB 与 Qt 连接

c++ - qml中拖动无框窗口 "jiggles"

c++ - Netbeans 中的标准输入

multithreading - 父GUI对话框线程的子线程可以创建子窗口吗?

python - 如何正确使用 SyncManager.Lock 或 Event?

.net - 我可以(安全地)在 ADO.NET 数据服务中使用 ThreadStatic 属性吗?

c++ - 成员是私有(private)的,C++ 中的运算符重载

c++ - 为什么我的 C++ 类方法的第一次调用非常昂贵?

c++ - 在 Makefile 中链接 SDL 库,c++

c++ - QListWidget内存泄漏