std::atomic<T>
and std::condition_variable
both have member wait
and notify_one
functions. In some applications, programmers may have a choice between using either for synchronization purposes. One goal with these wait
functions is that they should coordinate with the operating system to minimize spurious wakeups. That is, the operating system should avoid waking the wait
-ing thread until notify_one
or notify_all
are called.
On my machine, sizeof(std::atomic<T>)
is sizeof(T)
and sizeof(std::condition_variable)
is 72. If you exclude std::atomic<T>
's T
member, then std::condition_variable
reserves 72 bytes for to serve its synchronization purposes while sizeof(std::atomic<T>)
reserves 0 bytes.
My question: should I expect different behavior between std::condition_variable
's and std::atomic<T>
's wait
functions? For example, should std::condition_variable
have fewer spurious wakeups?
condition_variable
would take mutex with every wake to check wait condition, and release it when going back to wait. Locking/Releasing mutex is a service call to OS (well depends on implementation but usually is). I expect that 'atomic' would not need such guard to check wait condition. So 'atomic' does not need thread switching to acquire mutex at all. – CahoonT
changed, your processor need to switch to the calling thread. However, since 'atomic would not need such guard to check wait condition', switching threads in unnecessary. Another thread can check whether or not the atomic'sT
changed, and if it has, THEN wake the calling thread." This makes sense to me. I assume then that some OS process is in charge of checking if atomic'sT
changed (for ALL atomics currently waiting). – Dacycv.wait()
releases mutex when going to sleep and locking it again when wakes up because of notification. If mutex is locked by other thread, thread holdingcv
would go to sleep once again until mutex is released by other thread. Oncecv
acquire mutex after all, it could check wait condition. Atomic does not need mutex and potentially could cause lesser thread context switching. – Cahoon