title: C++ understanding multithreading with global variables
body: <p>I have a C++ program which declares some global variables. After that it splits up into several threads to do several tasks.
  Those threads read and write some of these global variables.</p>
  
  <p>Will there be an app-crash if two threads are <strong><em>reading</em></strong> the same variable? Or will there be an app-crash only if one thread <strong><em>writes</em></strong> to a variable which another thread is currently reading?</p>
  
  <p>So if the answer to my second question would be yes, would the following code sample solve this problem?</p>
  
  <pre><code>#include &lt;string&gt;
  #include &lt;thread&gt;
  #include &lt;mutex&gt;
  using namespace std;
  
  mutex m;
  string var = "foo";
  
  // function to provide read and write access
  // "protected" with mutex
  string test(string value = "")
  {
      m.lock();
      if (value == "")
      {
          m.unlock();
          return var;
      }
      else
      {
          var = value;
          m.unlock();
          return "";
      }
  }
  
  void thread1()
  {
      // use global variable local
      string localVar = test();
  }
  void thread2()
  {
      // overwrite global variable
      test("bar");
  }
  void thread3()
  {
      // use global variable local
      string localVar = test();
  }
  
  int main()
  {    
      thread t1(thread1);
      thread t2(thread2);
      thread t3(thread3);
  
      t1.join();
      t2.join();
      t3.join();
  
      return 0;
  }
  </code></pre>
  
  <p>furthermore: is this part </p>
  
  <pre><code>// ...
  if (value == "")
  {
      m.unlock();
      return var;
  }
  // ...
  </code></pre>
  
  <p>also thread-save?</p>
  
  <p>And my last question: my program currently uses only one mutex to prevent that two threads (the same function!) are running simultaneously. I am not using mutexes for my global variables. Could it be that this "situation" can cause an app-crash (module: "ntdll.dll") with the exception code 0xc0000005 ?</p>
  
  <p>Thanks in advance! </p>