TL;DR: What is meant by saying a specific function is 'thread-safe' as a data race occurs by simultaneously calling two possibly different functions? This question is especially relevant in the context of people telling "const means/implies thread-safe in C++11" [1][2]
Consider the following example:
class X {
int x, y; // are some more complex type (not supported by `std::atomic`)
std::mutex m;
public:
void set_x (int new_x) {x = new_x;} // no mutex
void get_x () const {return x;}
void set_y (int new_y) {
std::lock_guard<std::mutex> guard(m); // guard setter with mutex
y = new_y;
}
void get_y () const {return y;}
}
Is set_x
thread safe?
Off course, set_x
is not thread safe as calling it from two threads simultaneously results in a data race.
Are get_x
, get_y
and set_y
thread safe?
Two possible reasonings exists:
- Yes, they are thread safe, as calling
get_x
/get_y
/set_y
from two threads simultaneously does not result in a data race. - No, they are not thread safe, as calling
get_x
(orget_y
) andset_x
(orset_y
) from two threads simultaneously results in a data race.
Which one is the correct reasoning for each of those three functions?
Question summary
Which reasoning is correct?
- A function is thread safe iff calling it from two threads simultaneously does not result in a data race. Could work for
set_x
/get_x
, but fails forset_y
/get_y
, as this would result to the conclusion thatset_y
andget_y
are thread safe, but classY
isn't as callingset_y
andget_y
from two threads simultaneously results in a data race. - A function is thread safe iff it does not access any memory that could be modified without internal synchronization by another function. This seems to me the most consistent option, but is not the way it is often used (see related threads).
Related threads
Note that I have read the following related threads:
- Does const mean thread-safe in C++11? ['mean' = it's your duty to make it]
- How do I make a function thread safe in C++?
- https://isocpp.org/blog/2012/12/you-dont-know-const-and-mutable-herb-sutter
- https://softwareengineering.stackexchange.com/questions/379516/is-the-meaning-of-const-still-thread-safe-in-c11