title: How many times may a loop be executed in a multithreaded C++ program?
body: <p>This is an interview question. </p>
  
  <pre><code>class X 
  {
      int i = 0 ;
  
  public: 
      Class *foo()
      {
          for (  ;  i &lt; 1000 ; ++i )
          {
              // some code but do not change value of i 
          }
      }
  }    
  
  int main()
  {
      X myX ; 
      Thread  t1 = create_thread( myX.foo() ) ;
      Thread  t2 = create_thread( myX.foo() ) ; 
      Start t1 ...
      Start t2 ...
      join(t1)
      joint(t2)
  }
  </code></pre>
  
  <p>Q1: if the code run on 1-cpu processor, how many times can the for-loop run in worst case?</p>
  
  <p>Q2: what if the code run on 2-cpu processor, how many times can the for-loop run in worst case? </p>
  
  <p>My ideas:</p>
  
  <p>The loop may run infinite times, because a thread can run it many times before the other thread updates the value of <code>i</code>.  </p>
  
  <p>Or, when t1 is suspended, t2 runs 1000 times and then we have 1000 x 1000 times ? </p>
  
  <p>Is this correct?</p>