Sometimes we hear the notion that const means thread safety. It’s not that simple.
On my post about const correctness I got a few replies mentioning thread safety. Indeed I did not touch the topic back then because it deserves its own blog post.
What is all the fuzz about thread safety const?
Sometimes people seem to think that having a `const` variable automatically means it is safe to access it in multiple threads. This is a bit of an oversimplification.
What is true is that immutable data can be accessed without further precautions from multiple threads. This is simply because if the data is immutable that means we don’t write to it, and reading it will always give the same values. It does not matter how an when and from which thread we read it, so it is threadsafe.
But while we can express immutability by making the variables that hold that data `const`, the reverse is not true. `const` does not always mean immutable data.
In that article about const correctness I touched the two main points how we can change data through a `const` object. It may have `mutable` members, and it may have pointers to other data. This indirection is not checked by the compiler, i.e. the referenced data is not syntactically const.
The opposite may also hold, i.e. that some data is immutable and therefore threadsafe, even if we access it through a interface that is not explicitly declared `const`. This is of course only bad style and we can fix it by making the interface const correct.
So should I ban `mutable` and make all indirections also `const`?
Short answer: No.
We should of course better think twice before we use `mutable` and indirections. They make it harder to reason about the thread safety of our data, but that does not mean that those features have no place in multithreaded code.
Not all data needs to be shared between threads. Therefore, using classes that are not threadsafe is perfectly fine if only one thread ever accesses it. On the other hand, if we need to make our classes thread safe, making our data immutable is probably the easiest way to do so. But it’s not the only way.
Mutexes and all the other language features aimed to assist in creating threadsafe classes are the other way. And yes, there are lock free data structures that we theoretically can write. However, unless you are very smart and have lots of time, better do not try to design your own lock free data. It is very hard and you probably need help to prove and cross check the correctness of your design.
C++ gives us a lot of freedom to chose between different features. We should not constrain our choices just to be able to replace proper thinking about thread safety with a simple “const means thread safety” rule.