8

I have discovered through trial and error that the MATLAB engine function is not completely thread safe.

Does anyone know the rules?

Discovered through trial and error:

On Windows, the connection to MATLAB is via COM, so the COM Apartment threading rules apply. All calls must occur in the same thread, but multiple connections can occur in multiple threads as long as each connection is isolated.

From the answers below, it seems that this is not the case on UNIX, where calls can be made from multiple threads as long as the calls are made serially.

Amro
  • 123,847
  • 25
  • 243
  • 454
Jeremy
  • 2,321
  • 3
  • 21
  • 24
  • afaik MATLAB Engine is implemented using COM on Windows, and using pipes on Unix: http://www.mathworks.com/help/matlab/matlab_external/using-matlab-engine.html – Amro May 21 '13 at 23:23

4 Answers4

7

From the documentation,

MATLAB libraries are not thread-safe. If you create multithreaded applications, make sure only one thread accesses the engine application.

Jacob
  • 34,255
  • 14
  • 110
  • 165
3

When I first started using the engine, I didn't run across any documentation on thread safety, so I assumed that it was not thread-safe.

I use a C++ class to synchronize access to an engine instance. For more parallel processing designs, I instantiate multiple instances of the engine class.

(edit) I'm using MATLAB R14 on Solaris. I open the engine using the 'engOpen' call, and close it using 'engClose'. My platform does not crash when the Close is called by a different thread than the one that called Open.

Adam Holmberg
  • 7,245
  • 3
  • 30
  • 53
  • Your application does not crash because you are accessing the engine on different threads on Solaris. On windows and because of the limitations of COM objects, it will crash. – TonySalimi Nov 08 '21 at 09:52
2

From a user's perspective, Matlab's interpreter is purely single-threaded. To be safe, you probably need to make all access to the engine from a single thread.

Note that internally, Matlab uses plenty of threads. There are GUI threads, and in the last few versions, the interpreter can use multiple threads behind the scenes. But, the interpreter is semantically equivalent to a single-threaded interpreter (with interrupts).

Mr Fooz
  • 109,094
  • 6
  • 73
  • 101
0

You can use engOpenSingleUse instead of using engOpen to make more than one thread working separately. (Only Windows)

Shai
  • 111,146
  • 38
  • 238
  • 371
8888q8888
  • 55
  • 1
  • 5