Reputation: 33
I have a Qt GUI application that is doing some important real time work which must not be interrupted at all costs (Forwarding some incoming Serial traffic over LAN). At the moment the application is running flawless when there is no interaction with the GUI, but as soon as you click on a button or drag the form around, it seems like the forwarding is stopped for the time the click is being processed. Forwarding is done in a QTimer loop which I already put on a different thread than the GUI thread, but no change in the outcome. Here's some parts of the code:
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);
}
}
}
}
As I said earlier, this code is running fine under idle circumstances without any data loss. Am I doing something wrong?
Upvotes: 1
Views: 1022
Reputation: 105
It is a good idea to run you important real time work in another thread. The GUI thread or main should do drawing and the other one should do processing.
Qt's documentation about GUI thread says:
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.
And also when to use multithreading
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.
In your case running the realtime processing in separate thread will fix UI lagging issues and also will fix realtimeness issue.
I suggest you to read Threading basics from Qt's doc.
Upvotes: 1