title: Can Multiple Threads Read The Same Class Member Variable?
body: <p>Can multiple threads safely read the same class member variable without creating a race condition?</p>
  
  <pre><code>class foo {
      int x;
  };
  
  void Thread1(foo* bar) {
      float j = bar-&gt;x * 5;
  }
  
  void Thread2(foo* bar) {
      float k = bar-&gt;x / 5;
  }
  </code></pre>
  
  <p>So if for example, we have two threads running <code>Thread1</code> and <code>Thread2</code>. If each thread is passed the <em>same</em> <code>foo</code> 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?</p>
  
  <p>If the above <em>is</em> safe, can a third thread safely write to that same <code>foo</code> object as long as it doesn't touch <code>foo::x</code>?</p>
  
  <pre><code>#include &lt;thread&gt;
  
  class foo {
  public:
      int x = 1;
      int y = 1;
  };
  
  void Thread1(foo* bar) {
      int j;
      for (int i = 0; i &lt; 1000; i++) {
          j = bar-&gt;x * 5;
      }
      printf("T1 - %i\n", j);
  }
  
  void Thread2(foo* bar) {
      int k;
      for (int i = 0; i &lt; 1000; i++) {
          k = bar-&gt;x / 5;
      }
      printf("T2 - %i\n", k);
  }
  
  void Thread3(foo* bar) {
      for (int i = 0; i &lt; 1000; i++) {
          bar-&gt;y += 3;
      }
      printf("T3 - %i\n", bar-&gt;y);
  }
  
  int main() {
      foo bar;
  
      std::thread t1(Thread1, &amp;bar);
      std::thread t2(Thread2, &amp;bar);
      std::thread t3(Thread3, &amp;bar);
  
      t1.join();
      t2.join();
      t3.join();
  
      printf("x %i, y %i\n", bar.x, bar.y);
  
      return 0;
  }
  </code></pre>