Another threads problem
-
Hi,
I have simple modbus communication in new thread, smoe like below:void qmodbus::run(){ . . . //define write command function auto send_wr_cmd= [&](const quint16 cmd){ wr_cmd.setValue(1,cmd); reply_wr_cmd=mc.sendWriteRequest(wr_cmd,1); //new Request modbus adress 1 if(reply_wr_cmd->isFinished()){ delete reply_wr_cmd; }else{ connect(wr_reply,&QModbusReply::finished,wr_rpl_redy); //set callback function when reply ready. call[0] } }; . . . connect(this, &qmodbus::write_command, send_wr_cmd); if (!mc.connectDevice()){ exit(); return; } exec(); //qt event loop }
Where I try write to modbus form outside thread by connect signals:
connect(this, &Inverter::write_command, mbus, &qmodbus::write_command);
and I have a problem:
QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QModbusTcpClient(0x4b0f854), parent's thread is qmodbus(0xbf4680), current thread is QThread(0xbbb2c8)but it works the other way round:
connect(mbus, &qmodbus::updateData, this, &Inverter::updateData);
why ?
-
Hi,
I have simple modbus communication in new thread, smoe like below:void qmodbus::run(){ . . . //define write command function auto send_wr_cmd= [&](const quint16 cmd){ wr_cmd.setValue(1,cmd); reply_wr_cmd=mc.sendWriteRequest(wr_cmd,1); //new Request modbus adress 1 if(reply_wr_cmd->isFinished()){ delete reply_wr_cmd; }else{ connect(wr_reply,&QModbusReply::finished,wr_rpl_redy); //set callback function when reply ready. call[0] } }; . . . connect(this, &qmodbus::write_command, send_wr_cmd); if (!mc.connectDevice()){ exit(); return; } exec(); //qt event loop }
Where I try write to modbus form outside thread by connect signals:
connect(this, &Inverter::write_command, mbus, &qmodbus::write_command);
and I have a problem:
QSocketNotifier: Socket notifiers cannot be enabled or disabled from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QModbusTcpClient(0x4b0f854), parent's thread is qmodbus(0xbf4680), current thread is QThread(0xbbb2c8)but it works the other way round:
connect(mbus, &qmodbus::updateData, this, &Inverter::updateData);
why ?
@Damian7546 said in Another threads problem:
why ?
Because mc is not in the correct thread - simply calling an object in another thread without properly moving (or directly creating) it there will not work.
Please read the docs: https://doc.qt.io/qt-6/thread-basics.htmlThere is no need to use a thread here at all - use signals and slots from QModbusReply: https://doc.qt.io/qt-6/qmodbusreply.html