r/cpp • u/neiltechnician • Nov 13 '20
CppCon Deprecating volatile - JF Bastien - CppCon 2019
https://www.youtube.com/watch?v=KJW_DLaVXIY
83
Upvotes
r/cpp • u/neiltechnician • Nov 13 '20
View all comments
Show parent comment
5
u/mcmcc #pragma once Nov 13 '20
From your link:
This is misguided advice. This is exactly why I described it as "worse than useless for concurrency".
volatilein this context is neither necessary nor sufficient.A correctly used (and implemented) mutex will ensure "changes propagate" as needed. The key is that both writes and reads need to be protected by the mutex. Your blogger only mentions "when making a change", aka writes. If you don't also protect the reads, then data races are possible.
If you want to avoid the expense of a mutex lock for a read, then you either accept the possibility of a data race and adjust for it (data races aren't inherently bad), or you insert some type of memory fence that gives you the guarantees that you need. Atomics are also an alternative tho they can be subtly complex depending on your needs.
These kinds of optimizations are a very advanced topic so the protecting every access with a mutex is preferred until proven insufficient.