Do I need a memory barrier for a change notification flag between threads?

前端 未结 3 2015
一生所求
一生所求 2021-02-06 11:54

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

3条回答
  •  北海茫月
    2021-02-06 12:33

    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.

提交回复
热议问题