title: c++11 thread unknown output
body: <p>I  return to  c++ programming, therefore, I am trying a lot of things to master new c++ standard. I know the code I provided is very bad. I think I know how to fix it.  </p>
  
  <p>code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  
  using namespace std;
  
  void apple (string const&amp; x)
  {
                  cout &lt;&lt; "aaa" &lt;&lt; endl;
  }
  
  void orange()
  {
                  //string s = "hello";
                  thread t(apple,"hello");
                  t.detach();
  }
  
  int main() {
                  orange();
                  cout &lt;&lt; "!!!Hello World!!!" &lt;&lt; endl; // prints !!!Hello World!!!
                  return 0;
  }
  </code></pre>
  
  <p>one kind of outputs:</p>
  
  <pre><code>!!!Hello World!!!
  aaa
  aaa
  </code></pre>
  
  <p>from the code, we can see the "aaa" should be printed once. 
  my question is why there are two "aaa" on the output. what cause this problem?</p>
  
  <p>many thanks</p>
  
  <p>edit:
  added system info:</p>
  
  <pre><code>Using built-in specs.
  COLLECT_GCC=/usr/bin/g++
  COLLECT_LTO_WRAPPER=/usr/libexec/gcc/x86_64-redhat-linux/4.6.3/lto-wrapper
  Target: x86_64-redhat-linux
  Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --with-bugurl=http://bugzilla.redhat.com/bugzilla --enable-bootstrap --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-gnu-unique-object --enable-linker-build-id --enable-languages=c,c++,objc,obj-c++,java,fortran,ada,go,lto --enable-plugin --enable-java-awt=gtk --disable-dssi --with-java-home=/usr/lib/jvm/java-1.5.0-gcj-1.5.0.0/jre --enable-libgcj-multifile --enable-java-maintainer-mode --with-ecj-jar=/usr/share/java/eclipse-ecj.jar --disable-libjava-multilib --with-ppl --with-cloog --with-tune=generic --with-arch_32=i686 --build=x86_64-redhat-linux
  Thread model: posix
  gcc version 4.6.3 20120306 (Red Hat 4.6.3-2) (GCC) 
  </code></pre>
  
  <p>some other outputs:</p>
  
  <p>type A:</p>
  
  <pre><code>!!!Hello World!!!
  aaaaaa
  </code></pre>
  
  <p>typeB:</p>
  
  <pre><code>!!!Hello World!!!
  </code></pre>
  
  <p>typeC:</p>
  
  <pre><code>!!!Hello World!!!
  aaaaaa
  </code></pre>
  
  <p>typeD:</p>
  
  <pre><code>!!!Hello World!!!
  aaa
  &lt;empty line&gt;
  </code></pre>
  
  <p>edit:
  according @mark's answer. this is an undefined behavior.<br>
  I added a "sleep(1);" before main return. it gives me only one type of output. now i got confused, if it is undefined, why i didnt see other types of  output?</p>
  
  <p>output:</p>
  
  <pre><code>!!!Hello World!!!
  aaa
  </code></pre>