Can multiple threads safely read the same class member variable without creating a race condition?
class foo {
int x;
};
void Thread1(foo* bar) {
float j = bar->x * 5;
}
void Thread2(foo* bar) {
float k = bar->x / 5;
}
So if for example, we have two threads running Thread1
and Thread2
. If each thread is passed the same foo
object, can they run independantly, without race conditions, because we are only reading the variable and not writing? Or is the act of accessing the object make this whole thing unsafe?
If the above is safe, can a third thread safely write to that same foo
object as long as it doesn't touch foo::x
?
#include <thread>
class foo {
public:
int x = 1;
int y = 1;
};
void Thread1(foo* bar) {
int j;
for (int i = 0; i < 1000; i++) {
j = bar->x * 5;
}
printf("T1 - %i\n", j);
}
void Thread2(foo* bar) {
int k;
for (int i = 0; i < 1000; i++) {
k = bar->x / 5;
}
printf("T2 - %i\n", k);
}
void Thread3(foo* bar) {
for (int i = 0; i < 1000; i++) {
bar->y += 3;
}
printf("T3 - %i\n", bar->y);
}
int main() {
foo bar;
std::thread t1(Thread1, &bar);
std::thread t2(Thread2, &bar);
std::thread t3(Thread3, &bar);
t1.join();
t2.join();
t3.join();
printf("x %i, y %i\n", bar.x, bar.y);
return 0;
}