title: My C++ Unity plugin runs once in the editor but not twice
body: <p>I have a plugin that calls C++ code. When the game starts, it calls this <code>extern</code> C++ function:</p>
  
  <pre><code>void startPlugin() {
    MyClass::instance = new MyClass();
    MyClass::instance-&gt;process();
  }
  </code></pre>
  
  <p>The <code>process</code> method runs an infinite loop that processes data and goes on, as long at the <code>keepRunning</code> member is true. Because it runs an infinite loop and blocks, this method is called within its own thread.</p>
  
  <p>When the game ends I run this <code>extern</code> method from C#:</p>
  
  <pre><code>void stopPlugin() {
    MyClass::instance-&gt;keepRunning = false;
    sleep(1); // Make sure the process loop is done. It should take less than one frame, but just to be sure...
    MyClass::cleanup();
  }
  </code></pre>
  
  <p>Which refers to this method:</p>
  
  <pre><code>void MyClass::cleanup() {
    delete instance;
    instance = NULL;
  }
  </code></pre>
  
  <p>Based on what the console says, these methods are indeed run.</p>
  
  <p>On Mac, this works the first time. I can start the game in the editor and stop it in the editor and everything works fine. But if I try to run it a second time without restarting the Unity editor, the whole editor freezes. Sometimes it takes three times instead of two, but invariably the second or third attempt to play freezes Unity completely. The cursor changes to the spinning pinwheel.</p>
  
  <p>The log says:</p>
  
  <pre><code>Starting.
  
  (Filename: /Applications/buildAgent/work/d63dfc6385190b60/artifacts/MacEditorGenerated/UnityEngineDebug.cpp Line: 49)
  
  Receiving unhandled NULL exception
  Launching bug reporter
  Obtained 37 stack frames.
  #0  0x00000090019390 in _platform_memmove$VARIANT$sse42
  </code></pre>
  
  <p>And then the stack trace brings up the function that calls the <code>extern</code> function.</p>
  
  <p>Trying to join the thread that was running <code>startPlugin</code> freezes the editor on stop. I don't think it should do that. After all, at that stage, the loop is over and the instance cleaned. This is not guesswork, there are visible side effects: ending the loop turns off the computer's camera and I can see the light of the camera go off. Also a debug message is sent in C# after the call to <code>startPlugin</code> returns. So there is no doubt that the loop is over.</p>
  
  <p>A previous version that does not delete the instance works every time on Windows.</p>
  
  <p>Am I doing something obviously wrong?</p>