What is the relationship between const and thread safety?
Short answer
In modern C++, const on member functions is expected to be thread-safe for concurrent reads: the standard library assumes const operations can be called concurrently.
Advertisement
AModel answer
In modern C++, const on member functions is expected to be thread-safe for concurrent reads: the standard library assumes const operations can be called concurrently. This means a const method that mutates a mutable member (e.g., a cache) must synchronize (e.g., with a mutex) to remain safe. So const signals 'safe to call concurrently', which imposes obligations on mutable state.
mutable std::mutex m;
int get() const { std::lock_guard lk(m); return compute(); }Real-world example
A const accessor that lazily caches must lock a mutable mutex to be safe for concurrent callers.
Likely follow-ups
- What does const imply for concurrency? | What must mutable members do under const?
Related topics