Mutex to device simultaneous access
-
Hi, I have a question. I'm creating an application that needs to access a device via the serial port. Communication always takes place by sending a buffer and receiving the response buffer from the device, generally the device responds in about 200 milliseconds.
Access to the device takes place from a function that is executed periodically by a QML Timer and also by the user through some buttons in the ui. The problem here is how to avoid the situation in which the user tries to access the device at the same time as the Timer function also tries to do it.
I thought about using a MUTEX, but I'm not an expert and I don't know if it's the right solution, could it work well? Is there a better way to do this?
In case the mutex was the best solution, the function that accesses the device could be done in this way:
QByteArray deviceAccess(QByteArray query) { serialport_mutex.lock(); QByteArray readDataBuffer = serialPort.readAll(); while (serialPort.waitForReadyRead(5000)) readDataBuffer.append(serialPort.readAll()); if(dataComplete(readDataBuffer)) break; serialport_mutex.unlock(); return readDataBuffer; }
Thanks in advance, Federico
-
@federico-massimi said in Mutex to device simultaneous access:
situation in which the user tries to access the device at the same time as the Timer function also tries to do it.
When you don't use thread this can't happen since then both actions are taking place in the main thread so no problems here.
-
Don't use the mutexes at all for locking the I/O access for QSerialPort, QAbstractSocket and other QIODevice classes.
-
@federico-massimi said in Mutex to device simultaneous access:
situation in which the user tries to access the device at the same time as the Timer function also tries to do it.
When you don't use thread this can't happen since then both actions are taking place in the main thread so no problems here.
@Christian-Ehrlicher I thought that by using a timer another thread would be generated, so in my case is it impossible that during the execution of the timer callback also the callback of a button (as example) can be executed?
-
When you don't create a separate thread there won't be any.
-
When you don't create a separate thread there won't be any.
@Christian-Ehrlicher ok, thanks a lot for the clarification