title: Asynchronous call to MATLAB's engEvalString
body: <p><strong>Edit 2:</strong> Problem solved, see my answer.</p>
  
  <p>I am writing a C++ program that communicates with MATLAB through the <a href="http://www.mathworks.ch/ch/help/matlab/matlab_external/using-matlab-engine.html" rel="nofollow">Engine API</a>. The C++ application is running on Windows 7, and interacting with MATLAB 2012b (32-bit).</p>
  
  <p>I would like to make a time-consuming call to the MATLAB engine, using <code>engEvalString</code>, but cannot figure out how to make the call asynchronous. No callback is necessary (but would be nice if possible).</p>
  
  <p>The following is a minimum example of what doesn't work.</p>
  
  <pre><code>#include &lt;boost/thread.hpp&gt;
  
  extern "C" {
      #include &lt;engine.h&gt;
  }
  
  int main()
  {
      Engine* eng = engOpen("");
      engEvalString(eng,"x=10");
      boost::thread asyncEval(&amp;engEvalString,eng,"y=5");
      boost::this_thread::sleep(boost::posix_time::seconds(10));
      return 0;
  }
  </code></pre>
  
  <p>After running this program, I switch to the MATLAB engine window and find:</p>
  
  <pre><code>» x
  x =
      10
  » y
  Undefined function or variable 'y'.
  </code></pre>
  
  <p>So it seems that the second call, which should set y=5, is never processed by the MATLAB engine.</p>
  
  <p>The thread definitely runs, you can check this by moving the <code>engEvalString</code> call into a local function and launching this as the thread instead.</p>
  
  <p>I'm really stumped here, and would appreciate any suggestions!</p>
  
  <p><strong>EDIT:</strong> As Shafik pointed out in his answer, the engine is not thread-safe. I don't think this should be an issue for my use case, as the calls I need to make are ~5 seconds apart, for a calculation that takes 2 seconds. The reason I cannot wait for this calculation, is that the C++ application is a "medium-hard"-real-time robot controller which should send commands at 50Hz. If this rate drops below 30Hz, the robot will assume network issues and close the connection.</p>