I need a very fast (in the sense \"low cost for reader\", not \"low latency\") change notification mechanism between threads in order to update a read cache:
The
Use C++ atomics and make updateAvailable
an std::atomic
. The reason for this is that it's not just the CPU that can see an old version of the variable but especially the compiler which doesn't see the side effect of another thread and thus never bothers to refetch the variable so you never see the updated value in the thread. Additionally, this way you get a guaranteed atomic read, which you don't have if you just read the value.
Other than that, you could potentially get rid of the lock, if for example the producer only ever produces data when updateAvailable
is false, you can get rid of the mutex because the std::atomic<>
enforces proper ordering of the reads and writes. If that's not the case, you'll still need the lock.