title: How to write thread-safe C# code for Unity3D?
body: <p>I'd like to understand how to write thread safe code.</p>
  
  <p>For example I have this code in my game:</p>
  
  <pre><code>bool _done = false;
  Thread _thread;
  
  // main game update loop
  Update()
  {
      // if computation done handle it then start again
      if(_done)
      {
          // .. handle it ...
          _done = false;
          _thread = new Thread(Work);
          _thread.Start();
      }
  }
  
  void Work()
  {
       // ... massive computation
  
       _done = true;
  }
  </code></pre>
  
  <p>If I understand it correctly, it may happened that main game thread and my <code>_thread</code> can have its own cached version of <code>_done</code>, and one thread may never see that <code>_done</code> changed in another thread?</p>
  
  <p>And if it may, how to solve it?</p>
  
  <ol>
  <li><p>Is it possible to solve by, only applying <code>volatile</code> keyword.</p></li>
  <li><p>Or is it possible to read and write value through <code>Interlocked</code>'s methods like <code>Exchange</code> and <code>Read</code>?</p></li>
  <li><p>If I surround <code>_done</code> read and write operation with <code>lock (_someObject)</code>, need I use <code>Interlocked</code> or something to prevent caching?</p></li>
  </ol>
  
  <p><strong>Edit 1</strong></p>
  
  <ol start="4">
  <li>If I define <code>_done</code> as <code>volatile</code> and call <code>Update</code> method from multiple threads. Is it possible that 2 threads will enter <code>if</code> statement before I assign <code>_done</code> to false?</li>
  </ol>