title: C++11 std::thread and virtual function binding
body: <p>I ran into a weird C++ code behaviour, not sure whether it's a compiler bug or simply undefined/unspecified behaviour of my code. Here is the code:</p>
  
  <pre><code>#include &lt;unistd.h&gt;
  #include &lt;iostream&gt;
  #include &lt;thread&gt;
  
  struct Parent {
      std::thread t;
  
      static void entry(Parent* p) {
          p-&gt;init();
          p-&gt;fini();
      }
  
      virtual ~Parent() { t.join(); }
  
      void start() { t = std::thread{entry, this}; }
  
      virtual void init() { std::cout &lt;&lt; "Parent::init()" &lt;&lt; std::endl; }
      virtual void fini() { std::cout &lt;&lt; "Parent::fini()" &lt;&lt; std::endl; }
  };
  
  struct Child : public Parent {
      virtual void init() override { std::cout &lt;&lt; "Child::init()" &lt;&lt; std::endl; }
      virtual void fini() override { std::cout &lt;&lt; "Child::fini()" &lt;&lt; std::endl; }
  };
  
  int main() {
      Child c;
  
      c.start();
      sleep(1); // &lt;========== here is it
  
      return 0;
  }
  </code></pre>
  
  <p>The output of the code would be the following, which isn't surprising:</p>
  
  <pre><code>Child::init()
  Child::fini()
  </code></pre>
  
  <p>However, if the function call "sleep(1)" is commented out, the output would be:</p>
  
  <pre><code>Parent::init()
  Parent::~fini()
  </code></pre>
  
  <p>Tested on Ubuntu 15.04, both gcc-4.9.2 and clang-3.6.0 show the same behaviour. Compiler options:</p>
  
  <pre><code>g++/clang++ test.cpp -std=c++11 -pthread
  </code></pre>
  
  <p>It looks like a race condition (the vtable not fully constructed before the thread starts). Is this code ill-formed ? a compiler bug ? or it's supposed to be like this ?</p>