title: Multithreading and sequence of instructions
body: <p>While learning multithread programming I've written the following code.</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;thread&gt;
  #include &lt;iostream&gt;
  #include &lt;cassert&gt;
  
  void check() {
      int a = 0;
      int b = 0;
      {
          std::jthread t2([&amp;](){
              int i = 0;
              while (a &gt;= b) {
                  ++i;
              }
              std::cout &lt;&lt; &quot;failed at iteration &quot; &lt;&lt; i &lt;&lt; &quot;\n&quot;
                        // I know at this point a and b may have changed
                        &lt;&lt; a &lt;&lt; &quot; &gt;= &quot; &lt;&lt; b &lt;&lt; &quot;\n&quot;;
              std::exit(0);
          });
          std::jthread t1([&amp;](){
              while (true) {
                  ++a;
                  ++b;
              }
          });
      }
  }
  
  int main() {
      check();
  }
  </code></pre>
  <p>Since <code>++a</code> always happens before <code>++b</code> a should be always greater or equal to b.
  But experiment shows that sometimes <code>b &gt; a</code>. Why? What causes it? And how can I enforce it?</p>
  <p>Even when I replace <code>int a = 0;</code> with <code>int a = 1000;</code> which makes all of this even more crazy.</p>
  <p>The program exits soon so no int overflow happens.
  I found no instructions reordering in assembly which might have caused this.</p>