A class that enables locking an HWritableStateVariable for exclusive access. More...
#include <HStateVariableLocker>
Public Member Functions | |
HStateVariableLocker (HWritableStateVariable *stateVariable) | |
~HStateVariableLocker () | |
void | unlock () |
void | relock () |
The HWritableStateVariable provides read-write access to its value. The methods HWritableStateVariable::value() and HWritableStateVariable::setValue() are thread-safe, but that is not enough when multiple value()
and setValue()
calls have to be performed serially. In other words, the following code is not thread-safe without additional measures:
void example() { HWritableStateVariable* sv = stateVariableByName("MyIntegerVariable")->writable(); quint32 count = sv->value().toUInt(&ok); sv->setValue(++count); // WRONG! The state variable might have been modified by another thread before // the call to setValue() is done, effectively overwriting the value of // the state variable with stale data. }
The correct and thread-safe way to do multiple consecutive operations that depend on former operations with a state variable is demonstrated in the following:
void example() { HWritableStateVariable* sv = stateVariableByName("MyIntegerVariable")->writable(); HStateVariableLocker svLocker(sv); // this will guarantee that we have exclusive access to the state variable // until the lock is destroyed or explicitly unlocked using // HStateVariableLocker::unlock() quint32 count = sv->value().toUInt(&ok); sv->setValue(++count); }
HStateVariableLockers
. However, the state variable will not be unlocked before the corresponding number of unlock() calls have been made. HStateVariableLocker | ( | HWritableStateVariable * | stateVariable | ) | [explicit] |
Creates a new instance and locks the state variable for exclusive access.
stateVariable | specifies the writable state variable that will be locked for exclusive access. |
~HStateVariableLocker | ( | ) |
void unlock | ( | ) |
Unlocks the state variable from exclusive access.
Unlocks the state variable from exclusive access if the state variable was locked by this thread and the number of unlock() calls matches the consecutive number of times the state variable has been locked by the current thread.
void relock | ( | ) |
Attempts to lock the state variable for exclusive access.
Attempts to lock the state variable for exclusive access if the state variable is not already locked by the instance, or block the current thread until the state variable can be locked for exclusive access.