This question asks if const
means thread-safe, which Herb Sutter's You don't know const
and mutable
talk answers well. But what about the opposite direction? If a function is thread-safe, should it thereby be marked const
? If not, when should a function be marked const
?
Asked
Active
Viewed 105 times
1
-
You can easily construct a function that modifies state and is still thread-safe by providing appropriate synchronization mechanisms. It doesn't necessarily have to be `const`, unless I completely misunderstood your question – Alejandro Apr 22 '15 at 03:08
1 Answers
1
No, it's perfectly possible for a method to be non const
but still be thread safe. Either it uses atomics, or a lock to protect member variables. For example, the count()
method below is thread safe, whilst modifying the m_count
member variable.
#include <iostream>
#include <mutex>
class Counter
{
public:
Counter() : m_counterMutex(), m_counter(0) {}
unsigned int count() {
std::lock_guard<std::mutex> lk(m_counterMutex);
++m_counter;
return m_counter;
}
private:
std::mutex m_counterMutex;
unsigned int m_counter;
};
It shouldn't be marked as const
because the visible state has changed. It would surprise to users of the class that they could pass a const Counter&
object to a function and the visible state of the object could be changed by that function.

Steve
- 7,171
- 2
- 30
- 52
-
This is where I ended up too. It seems the real lesson of the talk is "const things should be logically const and thread-safe", not just "const should be thread-safe" – Shea Levy Apr 27 '15 at 23:12