Search code examples
c++multithreadingqtmodbus

Execute each QTModbus response in different thread


I'm developing Modbus application. Sending read requests like this.

void MainWindow::readData(int start,int len){

    QModbusDataUnit readUnit(QModbusDataUnit::InputRegisters,start,len);
    if (auto *reply = modbusDevice->sendReadRequest(readUnit,modbusAddr)) {
        if (!reply->isFinished())
            connect(reply, &QModbusReply::finished, this, &MainWindow::readReady);
        else
            delete reply; // broadcast replies return immediately
    }
}

As I have many read requests at the same time, I believe responses are 'stuck' in some kind of queue executing each readReady one-by-one, which is a bit slow.

I would like to execute each readReady in its own thread. Any way I could do it? Or, perhaps, this would be 'a bad practice'?

I've tried using QtConcurrent::run in readReady slot, but this doesn't really help.


Solution

  • I don't think the issue comes from readReady().

    As soon as a QModbusClient::sendReadRequest() is completed, you call the readReady() callback. You cannot go faster than the time it takes to the request to finish.

    If we take a look at the QModbusClient documentation, we can see this note:

    Note: QModbusClient queues the requests it receives. The number of requests executed in parallel is dependent on the protocol. For example, the HTTP protocol on desktop platforms issues 6 requests in parallel for one host/port combination.

    As you mentioned that you have "many requests at the same time", this may explain your issue.

    Actually I believe that the queuing you noticed is not about the readyRead() calls but about the QModbusClient side instead.

    Using multi-threading for the callback calls would not help since you cannot "put the cart before the horse" :)