title: Are read from and writing to vector thread-safe operations in vector C++?
body: <p>I have a below code that gives segmentation fault sometime?</p>
  
  <pre><code>vector&lt;int&gt; myvector;
  void function1()
  {
      for(int i = 0;i&lt;10;i++)
      {
          cout&lt;&lt;"writer thread:"&lt;&lt;i&lt;&lt;endl;
          myvector.push_back(i);
      }
  }
  void function2()
  {
      for(int i = 0;i&lt;10;i++)
      {
          cout&lt;&lt;"reader thread:";
          cout&lt;&lt;myvector[i]&lt;&lt;endl;
      }
  }
  int main()
  {
  
      thread t1(function1);
      thread t2(function2);
  
      t1.join();
      t2.join();
  }
  </code></pre>
  
  <p>I am little confused with the thread safe rules/guarantees on containers in general and vectors in particular. I was asked this question in an interview and failed to put in words why it write in on thread and write in other thread is not thread-safe operation.</p>
  
  <p>in the below link for push_back of vectors I see "Otherwise, no existing element is accessed, and concurrently accessing or modifying them is safe" under Data Race section. How does this statement justify that vector write operation is not thread-safe?</p>
  
  <p><a href="http://www.cplusplus.com/reference/vector/vector/push_back/" rel="nofollow noreferrer">http://www.cplusplus.com/reference/vector/vector/push_back/</a> </p>