In the situation where you have a high priority real-time data processing thread reading from a parameter and a second thread with lower priority writing to the parameter (or vice versa) you can end up with a data race.
One solution would be to let the parameter be an std::atomic
or to protect the reading/writing of the parameter with mutexes. According to this talk it's best to avoid non-lock free atomics and mutexes to solve such a data race for the following reasons:
- The real-time thread will occasionally have to wait to acquire the lock. The execution time of the real-time code, which has to meet a deadline, will suddenly have to take into account any code that can be executed inside the lock protected section of the low priority thread.
- If the code inside the lock protected section in the low priority thread contains e.g. memory allocations/deallocation, system calls, or other calls with unbounded execution time the real-time thread can no longer guarantee that it's able meet it's deadline.
- The low priority thread can be interrupted by threads which have a higher priority but a priority still below that of the real-time thread, leading to priority inversion.
If one can disregard the last point due to an OS with priority inheritance, is it still advisable to avoid locking even if all lock protected sections are contained inside the same class such as in this example:
#include <mutex>
class RealTimeProcessor
{
public:
struct Parameter
{
// some non atomic data
};
void processData()
{
Parameter p;
mtx.lock();
p = m_param;
mtx.unlock();
// do some processing with the local copy of the parameter...
}
void setParameter(Parameter param)
{
mtx.lock();
m_param = param;
mtx.unlock();
}
private:
Parameter m_param;
std::mutex mtx;
};
Where processData()
is called from the real-time thread and setParameter()
is called from the low priority thread.
My thought is that since all locking is done within the class, I can make sure that no calls with unbounded execution time are made within the lock protected areas, and that the total worst case completion time of the real-time processing still meets the deadline even in the worst case when having to wait to acquire the lock.