Matlab Engine closes unexpectedly after thread ends in C++

2 views (last 30 days)
I know that Matlab Engine API is not thread-safe. But for windows, I figure that with engOpenSingleUse(), multi-threaded may still be achievable. The idea here was to have the calculations from different objects (classes) operate on the same Matlab computational engine while they were in the same thread. Each thread then accesses its own interface which contains a valid Matlab engine pointer among those objects. and therefore, avoid conflict in my multi-thread application. Then I bumped in to this issue. The Mmatlab Engine closed itself after the thread ended, without calling engClose().
For testing purpose, I would want those Matlab engines remain open so I can perform additional checks and operations by entering code directly in the consoles.
After many tests, I finally realized that it's not about how I implement the Matlab engine because simply calling engOpen() or engOpenSingleUse() in thread would result in this issue.
Here is an example I use for test
void callback() {
Engine* ep = engOpenSingleUse(NULL,NULL,NULL);
int main(int argc, char *argv[])
std::shared_ptr<std::thread> thread1;
thread1 = std::make_shared<std::thread>(&callback);
std::shared_ptr<std::thread> thread2;
thread2 = std::make_shared<std::thread>(&callback);
return 1;
The code compiled and ran fine. Two instances of Matlab engines started and ran as expected. But somehow the Matlab engine I started along the thread closed itself without calling engClose().
If I didn't call the callback() using thread, e.g.
void main() {callback();}
The application ends with an opened Matlab engine, which is totally expected. But using the thread, all Matlab engines closed automatically.
Have anyone even encountered similar problem? I would like those instances remain open unless I instruct the close signal explicitly, otherwise I could lose control in my management class because the engine closes unexpectedly. Any thought is appreciated.

Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!